trace

package
v0.6.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 29, 2022 License: Apache-2.0 Imports: 27 Imported by: 0

Documentation

Index

Constants

View Source
const (
	InternalExecutor = "InternalExecutor"
	FileService      = "FileService"
)
View Source
const (
	MOStatementType = "statement"
	MOSpanType      = "span"
	MOLogType       = "log"
	MOErrorType     = "error"
	MORawLogType    = rawLogTbl
)
View Source
const (
	SystemDBConst = "system"
	StatsDatabase = SystemDBConst
)
View Source
const (
	// FlagsSampled is a bitmask with the sampled bit set. A SpanContext
	// with the sampling bit set means the span is sampled.
	FlagsSampled = TraceFlags(0x01)
)
View Source
const NodeTypeStandalone = "Standalone"
View Source
const SpanFieldKey = "span"

Variables

View Source
var (
	SingleStatementTable = &export.Table{
		Account:  export.AccountAll,
		Database: StatsDatabase,
		Table:    statementInfoTbl,
		Columns: []export.Column{
			stmtIDCol,
			txnIDCol,
			sesIDCol,
			accountCol,
			userCol,
			hostCol,
			dbCol,
			stmtCol,
			stmtTagCol,
			stmtFgCol,
			nodeUUIDCol,
			nodeTypeCol,
			reqAtCol,
			respAtCol,
			durationCol,
			statusCol,
			errCodeCol,
			errorCol,
			execPlanCol,
			rowsReadCol,
			bytesScanCol,
		},
		PrimaryKeyColumn: []export.Column{stmtIDCol},
		Engine:           export.ExternalTableEngine,
		Comment:          "record each statement and stats info",
		PathBuilder:      export.NewAccountDatePathBuilder(),
		AccountColumn:    &accountCol,

		SupportUserAccess: true,
	}

	SingleRowLogTable = &export.Table{
		Account:  export.AccountAll,
		Database: StatsDatabase,
		Table:    rawLogTbl,
		Columns: []export.Column{
			rawItemCol,
			nodeUUIDCol,
			nodeTypeCol,
			spanIDCol,
			traceIDCol,
			loggerNameCol,
			timestampCol,
			levelCol,
			callerCol,
			messageCol,
			extraCol,
			errCodeCol,
			errorCol,
			stackCol,
			spanNameCol,
			parentSpanIDCol,
			startTimeCol,
			endTimeCol,
			durationCol,
			resourceCol,
			spanKindCol,
		},
		PrimaryKeyColumn: nil,
		Engine:           export.ExternalTableEngine,
		Comment:          "read merge data from log, error, span",
		PathBuilder:      export.NewAccountDatePathBuilder(),
		AccountColumn:    nil,

		SupportUserAccess: false,
	}
)
View Source
var EndStatement = func(ctx context.Context, err error) {
	if !GetTracerProvider().IsEnable() {
		return
	}
	s := StatementFromContext(ctx)
	if s == nil {
		panic(moerr.NewInternalError("no statement info in context"))
	}
	s.mux.Lock()
	defer s.mux.Unlock()
	if !s.end {

		s.end = true
		s.ResponseAt = time.Now()
		s.Duration = s.ResponseAt.Sub(s.RequestAt)
		s.Status = StatementStatusSuccess
		if err != nil {
			s.Error = err
			s.Status = StatementStatusFailed
		}
		if !s.reported || s.exported {
			s.Report(ctx)
		}
	}
}
View Source
var QuoteFieldFunc = func(buf *bytes.Buffer, value string, enclose rune) string {
	replaceRules := map[rune]string{
		'"':  `""`,
		'\'': `\'`,
	}
	quotedClose, hasRule := replaceRules[enclose]
	if !hasRule {
		panic(moerr.NewInternalError("not support csv enclose: %c", enclose))
	}
	for _, c := range value {
		if c == enclose {
			buf.WriteString(quotedClose)
		} else {
			buf.WriteRune(c)
		}
	}
	return value
}
View Source
var ReportStatement = func(ctx context.Context, s *StatementInfo) error {
	if !GetTracerProvider().IsEnable() {
		return nil
	}
	return export.GetGlobalBatchProcessor().Collect(ctx, s)
}

Functions

func ContextField

func ContextField(ctx context.Context) zap.Field

func ContextWithSpan

func ContextWithSpan(parent context.Context, span Span) context.Context

func ContextWithSpanContext

func ContextWithSpanContext(parent context.Context, sc SpanContext) context.Context

func ContextWithStatement

func ContextWithStatement(parent context.Context, s *StatementInfo) context.Context

func DebugMode

func DebugMode(debug bool) tracerProviderOption

func DefaultContext

func DefaultContext() context.Context

func EnableTracer

func EnableTracer(enable bool) tracerProviderOption

func GetSchemaForAccount

func GetSchemaForAccount(account string) []string

GetSchemaForAccount return account's table, and view's schema

func Init

func InitSchema

func InitSchema(ctx context.Context, sqlExecutor func() ie.InternalExecutor) error

InitSchema PS: only in standalone or CN node can init schema

func InitSchemaByInnerExecutor

func InitSchemaByInnerExecutor(ctx context.Context, ieFactory func() ie.InternalExecutor) error

InitSchemaByInnerExecutor init schema, which can access db by io.InternalExecutor on any Node.

func IsSpanField

func IsSpanField(field zapcore.Field) bool

func NewBufferPipe2CSVWorker

func NewBufferPipe2CSVWorker(opt ...bufferOption) bp.PipeImpl[bp.HasName, any]

func ReportError

func ReportError(ctx context.Context, err error, depth int)

ReportError send to BatchProcessor

func ReportZap

func ReportZap(jsonEncoder zapcore.Encoder, entry zapcore.Entry, fields []zapcore.Field) (*buffer.Buffer, error)

func SetDefaultContext

func SetDefaultContext(ctx context.Context)

func SetDefaultSerializeExecPlan

func SetDefaultSerializeExecPlan(f SerializeExecPlanFunc)

func SetDefaultSpanContext

func SetDefaultSpanContext(sc *SpanContext)

func SetTracerProvider

func SetTracerProvider(p *MOTracerProvider)

func Shutdown

func Shutdown(ctx context.Context) error

func SpanField

func SpanField(sc SpanContext) zap.Field

func WithBatchProcessMode

func WithBatchProcessMode(mode string) tracerProviderOption

func WithExportInterval

func WithExportInterval(secs int) tracerProviderOption

func WithFSWriterFactory

func WithFSWriterFactory(f export.FSWriterFactory) tracerProviderOption

func WithInitAction

func WithInitAction(init bool) tracerProviderOption

func WithLongQueryTime

func WithLongQueryTime(secs float64) tracerProviderOption

func WithMOVersion

func WithMOVersion(v string) tracerProviderOption

func WithNewRoot

func WithNewRoot(newRoot bool) spanOptionFunc

func WithNode

func WithNode(uuid string, t string) tracerProviderOption

WithNode give id as NodeId, t as NodeType

func WithSQLExecutor

func WithSQLExecutor(f func() ie.InternalExecutor) tracerProviderOption

func WithSpanID

func WithSpanID(id SpanID) spanOptionFunc

func WithTraceID

func WithTraceID(id TraceID) spanOptionFunc

Types

type CSVRequest

type CSVRequest struct {
	// contains filtered or unexported fields
}

func NewCSVRequest

func NewCSVRequest(writer io.StringWriter, content string) *CSVRequest

func (*CSVRequest) Content

func (r *CSVRequest) Content() string

func (*CSVRequest) Handle

func (r *CSVRequest) Handle() (int, error)

type CSVRequests

type CSVRequests []*CSVRequest

type CsvFields

type CsvFields interface {
	bp.HasName
	GetRow() *export.Row
	CsvFields(row *export.Row) []string
}

type IBuffer2SqlItem

type IBuffer2SqlItem interface {
	bp.HasName
	Size() int64
	Free()
}

type IDGenerator

type IDGenerator interface {
	NewIDs() (TraceID, SpanID)
	NewSpanID() SpanID
}

type MOErrorHolder

type MOErrorHolder struct {
	Error     error     `json:"error"`
	Timestamp time.Time `json:"timestamp"`
}

func (*MOErrorHolder) CsvFields

func (h *MOErrorHolder) CsvFields(row *export.Row) []string

func (*MOErrorHolder) Format

func (h *MOErrorHolder) Format(s fmt.State, verb rune)

func (*MOErrorHolder) Free

func (h *MOErrorHolder) Free()

func (*MOErrorHolder) GetName

func (h *MOErrorHolder) GetName() string

func (*MOErrorHolder) GetRow

func (h *MOErrorHolder) GetRow() *export.Row

func (*MOErrorHolder) Size

func (h *MOErrorHolder) Size() int64

type MONodeResource

type MONodeResource struct {
	NodeUuid string `json:"node_uuid"`
	NodeType string `json:"node_type"`
}

func GetNodeResource

func GetNodeResource() *MONodeResource

type MOSpan

type MOSpan struct {
	SpanConfig
	Name      bytes.Buffer `json:"name"`
	StartTime time.Time    `json:"start_time"`
	EndTime   time.Time    `jons:"end_time"`
	Duration  uint64       `json:"duration"`
	// contains filtered or unexported fields
}

func (*MOSpan) CsvFields

func (s *MOSpan) CsvFields(row *export.Row) []string

func (*MOSpan) End

func (s *MOSpan) End(options ...SpanEndOption)

func (*MOSpan) Free

func (s *MOSpan) Free()

func (*MOSpan) GetName

func (s *MOSpan) GetName() string

func (*MOSpan) GetRow

func (s *MOSpan) GetRow() *export.Row

func (*MOSpan) ParentSpanContext

func (s *MOSpan) ParentSpanContext() SpanContext

func (*MOSpan) Size

func (s *MOSpan) Size() int64

func (*MOSpan) SpanContext

func (s *MOSpan) SpanContext() SpanContext

type MOTracer

type MOTracer struct {
	TracerConfig
	// contains filtered or unexported fields
}

MOTracer is the creator of Spans.

func (*MOTracer) Debug

func (t *MOTracer) Debug(ctx context.Context, name string, opts ...SpanOption) (context.Context, Span)

func (*MOTracer) Start

func (t *MOTracer) Start(ctx context.Context, name string, opts ...SpanOption) (context.Context, Span)

type MOTracerProvider

type MOTracerProvider struct {
	// contains filtered or unexported fields
}

func GetTracerProvider

func GetTracerProvider() *MOTracerProvider

func (*MOTracerProvider) GetSqlExecutor

func (cfg *MOTracerProvider) GetSqlExecutor() func() ie.InternalExecutor

func (*MOTracerProvider) IsEnable

func (cfg *MOTracerProvider) IsEnable() bool

func (*MOTracerProvider) SetEnable

func (cfg *MOTracerProvider) SetEnable(enable bool)

func (*MOTracerProvider) Tracer

func (p *MOTracerProvider) Tracer(instrumentationName string, opts ...TracerOption) Tracer

type MOZapLog

type MOZapLog struct {
	Level       zapcore.Level `json:"Level"`
	SpanContext *SpanContext  `json:"span"`
	Timestamp   time.Time     `json:"timestamp"`
	LoggerName  string
	Caller      string `json:"caller"` // like "util/trace/trace.go:666"
	Message     string `json:"message"`
	Extra       string `json:"extra"` // like json text
	Stack       string `json:"stack"`
}

func (*MOZapLog) CsvFields

func (m *MOZapLog) CsvFields(row *export.Row) []string

func (*MOZapLog) Free

func (m *MOZapLog) Free()

func (*MOZapLog) GetName

func (m *MOZapLog) GetName() string

func (*MOZapLog) GetRow

func (m *MOZapLog) GetRow() *export.Row

func (*MOZapLog) Size

func (m *MOZapLog) Size() int64

Size 计算近似值

type Resource

type Resource struct {
	// contains filtered or unexported fields
}

func (*Resource) Get

func (r *Resource) Get(key string) (any, bool)

func (*Resource) Put

func (r *Resource) Put(key string, val any)

func (*Resource) String

func (r *Resource) String() string

String need to improve

type SerializeExecPlanFunc

type SerializeExecPlanFunc func(plan any, uuid2 uuid.UUID) (jsonByte []byte, rows int64, bytes int64)

type Span

type Span interface {
	// End completes the Span. The Span is considered complete and ready to be
	// delivered through the rest of the telemetry pipeline after this method
	// is called. Therefore, updates to the Span are not allowed after this
	// method has been called.
	End(options ...SpanEndOption)

	// SpanContext returns the SpanContext of the Span. The returned SpanContext
	// is usable even after the End method has been called for the Span.
	SpanContext() SpanContext

	ParentSpanContext() SpanContext
}

func Debug

func Debug(ctx context.Context, spanName string, opts ...SpanOption) (context.Context, Span)

func SpanFromContext

func SpanFromContext(ctx context.Context) Span

func Start

func Start(ctx context.Context, spanName string, opts ...SpanOption) (context.Context, Span)

type SpanConfig

type SpanConfig struct {
	SpanContext

	// NewRoot identifies a Span as the root Span for a new trace. This is
	// commonly used when an existing trace crosses trust boundaries and the
	// remote parent span context should be ignored for security.
	NewRoot bool `json:"NewRoot"` // WithNewRoot
	// contains filtered or unexported fields
}

SpanConfig is a group of options for a Span.

type SpanContext

type SpanContext struct {
	TraceID TraceID `json:"trace_id"`
	SpanID  SpanID  `json:"span_id"`
	// Kind default SpanKindInternal
	Kind SpanKind `json:"span_kind"`
}

SpanContext contains identifying trace information about a Span.

func DefaultSpanContext

func DefaultSpanContext() *SpanContext

func SpanContextWithID

func SpanContextWithID(id TraceID, kind SpanKind) SpanContext

func SpanContextWithIDs

func SpanContextWithIDs(tid TraceID, sid SpanID) SpanContext

SpanContextWithIDs with default Kind: SpanKindInternal

func (SpanContext) GetIDs

func (c SpanContext) GetIDs() (TraceID, SpanID)

func (*SpanContext) IsEmpty

func (c *SpanContext) IsEmpty() bool

func (*SpanContext) MarshalLogObject

func (c *SpanContext) MarshalLogObject(enc zapcore.ObjectEncoder) error

MarshalLogObject implement zapcore.ObjectMarshaler

func (*SpanContext) MarshalTo

func (c *SpanContext) MarshalTo(dAtA []byte) (int, error)

func (*SpanContext) Reset

func (c *SpanContext) Reset()

func (*SpanContext) Size

func (c *SpanContext) Size() (n int)

func (*SpanContext) Unmarshal

func (c *SpanContext) Unmarshal(dAtA []byte) error

Unmarshal with default Kind: SpanKindRemote

type SpanEndOption

type SpanEndOption interface {
	// contains filtered or unexported methods
}

type SpanID

type SpanID [8]byte

func (*SpanID) IsZero

func (s *SpanID) IsZero() bool

func (*SpanID) SetByUUID

func (s *SpanID) SetByUUID(id string)

SetByUUID use prefix of uuid as value

func (SpanID) String

func (s SpanID) String() string

type SpanKind

type SpanKind int

SpanKind is the role a Span plays in a Trace.

const (
	// SpanKindInternal is a SpanKind for a Span that represents an internal
	// operation within MO.
	SpanKindInternal SpanKind = 0
	// SpanKindStatement is a SpanKind for a Span that represents the operation
	// belong to statement query
	SpanKindStatement SpanKind = 1
	// SpanKindRemote is a SpanKind for a Span that represents the operation
	// cross rpc
	SpanKindRemote SpanKind = 2
)

func (SpanKind) String

func (k SpanKind) String() string

type SpanOption

type SpanOption interface {
	SpanStartOption
	SpanEndOption
}

SpanOption applies an option to a SpanConfig.

type SpanProcessor

type SpanProcessor interface {
	OnStart(ctx context.Context, s Span)
	OnEnd(s Span)
	Shutdown(ctx context.Context) error
}

func NewBatchSpanProcessor

func NewBatchSpanProcessor(exporter export.BatchProcessor) SpanProcessor

type SpanStartOption

type SpanStartOption interface {
	// contains filtered or unexported methods
}

SpanStartOption applies an option to a SpanConfig. These options are applicable only when the span is created.

type StatementInfo

type StatementInfo struct {
	StatementID          [16]byte  `json:"statement_id"`
	TransactionID        [16]byte  `json:"transaction_id"`
	SessionID            [16]byte  `jons:"session_id"`
	Account              string    `json:"account"`
	User                 string    `json:"user"`
	Host                 string    `json:"host"`
	Database             string    `json:"database"`
	Statement            string    `json:"statement"`
	StatementFingerprint string    `json:"statement_fingerprint"`
	StatementTag         string    `json:"statement_tag"`
	RequestAt            time.Time `json:"request_at"` // see WithRequestAt

	// after
	Status     StatementInfoStatus `json:"status"`
	Error      error               `json:"error"`
	ResponseAt time.Time           `json:"response_at"`
	Duration   time.Duration       `json:"duration"` // unit: ns
	ExecPlan   any                 `json:"exec_plan"`
	// RowsRead, BytesScan generated from ExecPlan
	RowsRead  int64 `json:"rows_read"`  // see ExecPlan2Json
	BytesScan int64 `json:"bytes_scan"` // see ExecPlan2Json
	// SerializeExecPlan
	SerializeExecPlan SerializeExecPlanFunc // see SetExecPlan, ExecPlan2Json
	// contains filtered or unexported fields
}

func StatementFromContext

func StatementFromContext(ctx context.Context) *StatementInfo

func (*StatementInfo) CsvFields

func (s *StatementInfo) CsvFields(row *export.Row) []string

func (*StatementInfo) ExecPlan2Json

func (s *StatementInfo) ExecPlan2Json() string

ExecPlan2Json return ExecPlan Serialized json-str and set RowsRead, BytesScan from ExecPlan

func (*StatementInfo) Free

func (s *StatementInfo) Free()

func (*StatementInfo) GetName

func (s *StatementInfo) GetName() string

func (*StatementInfo) GetRow

func (s *StatementInfo) GetRow() *export.Row

func (*StatementInfo) IsZeroTxnID

func (s *StatementInfo) IsZeroTxnID() bool

func (*StatementInfo) Report

func (s *StatementInfo) Report(ctx context.Context)

func (*StatementInfo) SetExecPlan

func (s *StatementInfo) SetExecPlan(execPlan any, SerializeFunc SerializeExecPlanFunc)

SetExecPlan record execPlan should be TxnComputationWrapper.plan obj, which support 2json.

func (*StatementInfo) SetTxnID

func (s *StatementInfo) SetTxnID(id []byte)

func (*StatementInfo) Size

func (s *StatementInfo) Size() int64

type StatementInfoStatus

type StatementInfoStatus int
const (
	StatementStatusRunning StatementInfoStatus = iota
	StatementStatusSuccess
	StatementStatusFailed
)

func (StatementInfoStatus) String

func (s StatementInfoStatus) String() string

type StatementOption

type StatementOption interface {
	Apply(*StatementInfo)
}

type StatementOptionFunc

type StatementOptionFunc func(*StatementInfo)

type TraceFlags

type TraceFlags byte //nolint:revive // revive complains about stutter of `trace.TraceFlags`.

TraceFlags contains flags that can be set on a SpanContext.

func (TraceFlags) IsSampled

func (tf TraceFlags) IsSampled() bool

IsSampled returns if the sampling bit is set in the TraceFlags.

func (TraceFlags) String

func (tf TraceFlags) String() string

String returns the hex string representation form of TraceFlags.

func (TraceFlags) WithSampled

func (tf TraceFlags) WithSampled(sampled bool) TraceFlags

WithSampled sets the sampling bit in a new copy of the TraceFlags.

type TraceID

type TraceID [16]byte

func (TraceID) IsZero

func (t TraceID) IsZero() bool

IsZero checks whether the trace TraceID is 0 value.

func (TraceID) String

func (t TraceID) String() string

type Tracer

type Tracer interface {
	// Start creates a span and a context.Context containing the newly-created span.
	Start(ctx context.Context, spanName string, opts ...SpanOption) (context.Context, Span)
	// Debug creates a span only with DebugMode
	Debug(ctx context.Context, spanName string, opts ...SpanOption) (context.Context, Span)
}

type TracerConfig

type TracerConfig struct {
	Name string
}

TracerConfig is a group of options for a Tracer.

type TracerOption

type TracerOption interface {
	// contains filtered or unexported methods
}

TracerOption applies an option to a TracerConfig.

type TracerProvider

type TracerProvider interface {
	Tracer(instrumentationName string, opts ...TracerOption) Tracer
}

type TracerProviderOption

type TracerProviderOption interface {
	// contains filtered or unexported methods
}

TracerProviderOption configures a TracerProvider.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL