go2sky

package module
v1.3.19 Latest Latest
Warning

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

Go to latest
Published: Apr 8, 2022 License: Apache-2.0 Imports: 15 Imported by: 0

README

GO2Sky

Build GoDoc

GO2Sky is an instrument SDK library, written in Go, by following Apache SkyWalking tracing and metrics formats.

Installation

$ go get -u github.com/powerapm/go2sky

The API of this project is still evolving. The use of vendoring tool is recommended.

Quickstart

By completing this quickstart, you will learn how to trace local methods. For more details, please view the example

Configuration

GO2Sky can export traces to Apache SkyWalking OAP server or local logger. In the following example, we configure GO2Sky to export to OAP server, which is listening on oap-skywalking port 11800, and all of the spans from this program will be associated with a service name example.

r, err := reporter.NewGRPCReporter("oap-skywalking:11800")
if err != nil {
   log.Fatalf("new reporter error %v \n", err)
}
defer r.Close()
tracer, err := go2sky.NewTracer("example", go2sky.WithReporter(r))

Create span

To create a span in a trace, we used the Tracer to start a new span. We indicate this as the root span because of passing context.Background(). We must also be sure to end this span, which will be show in End span.

span, ctx, err := tracer.CreateLocalSpan(context.Background())

Get Global TraceID

Get the TraceID of the activeSpan in the Context.

go2sky.TraceID(ctx)

Create a sub span

A sub span created as the children of root span links to its parent with Context.

subSpan, newCtx, err := tracer.CreateLocalSpan(ctx)

End span

We must end the spans so they becomes available for sending to the backend by a reporter.

subSpan.End()
span.End()

Advanced Concepts

We cover some advanced topics about GO2Sky.

Context propagation

Trace links spans belong to it by using context propagation which varies between different scenario.

In process

We use context package to link spans. The root span usually pick context.Background(), and sub spans will inject the context generated by its parent.

//Create a new context
entrySpan, entryCtx, err := h.tracer.CreateEntrySpan(context.Background(), ...)

// Some operation
...

// Link two spans by injecting entrySpan context into exitSpan
exitSpan, err := t.tracer.CreateExitSpan(entryCtx, ...)

Crossing process

We use Entry span to extract context from downstream service, and use Exit span to inject context to upstream service.

Entry and Exit spans make sense to OAP analysis which generates topology map and service metrics.

//Extract context from HTTP request header `sw6`
span, ctx, err := h.tracer.CreateEntrySpan(r.Context(), "/api/login", func() (string, error) {
		return r.Header.Get("sw6"), nil
})

// Some operation
...

// Inject context into HTTP request header `sw6`
span, err := t.tracer.CreateExitSpan(req.Context(), "/service/validate", "tomcat-service:8080", func(header string) error {
		req.Header.Set(propagation.Header, header)
		return nil
})

Tag

We set tags into a span which is stored in the backend, but some tags have special purpose. OAP server may use them to aggregate metrics, generate topology map and etc.

They are defined as constant in root package with prefix Tag.

Plugins

Plugins is integrated with specific framework, for instance, net/http, gin and etc. They are stored in plugins package.

  1. HTTP client/server example
  2. gin example
  3. go-resty example

License

Apache License 2.0. See LICENSE file for details.

Documentation

Overview

Package go2sky implements a native Apache SkyWalking agent library for Go.

See http://skywalking.apache.org/ for more information about Apache SkyWalking.

Index

Examples

Constants

View Source
const (
	EmptyTraceID = "N/A"
	NoopTraceID  = "[Ignored Trace]"
	// -1 represent the object doesn't exist.
	Inexistence = -1
)
View Source
const (
	EmptyServiceName         = ""
	EmptyServiceInstanceName = ""
	EmptyTraceSegmentID      = "N/A"
	EmptySpanID              = -1
)

Variables

This section is empty.

Functions

func SpanID added in v1.3.18

func SpanID(ctx context.Context) int32

func TraceID

func TraceID(ctx context.Context) string

func TraceSegmentID added in v1.3.18

func TraceSegmentID(ctx context.Context) string

2022-02-24 huangyao kratos插件支持v2协议

Types

type NoopSpan

type NoopSpan struct {
}

func (*NoopSpan) End

func (*NoopSpan) End()

func (*NoopSpan) Error

func (*NoopSpan) Error(time.Time, ...string)

func (*NoopSpan) GetOperationName

func (*NoopSpan) GetOperationName() string

func (*NoopSpan) IsEntry

func (*NoopSpan) IsEntry() bool

func (*NoopSpan) IsExit

func (*NoopSpan) IsExit() bool

func (*NoopSpan) Log

func (*NoopSpan) Log(time.Time, ...string)

func (*NoopSpan) SetComponent

func (*NoopSpan) SetComponent(int32)

func (*NoopSpan) SetOperationName

func (*NoopSpan) SetOperationName(string)

func (*NoopSpan) SetPeer

func (*NoopSpan) SetPeer(string)

func (*NoopSpan) SetSpanLayer

func (*NoopSpan) SetSpanLayer(common.SpanLayer)

func (*NoopSpan) Tag

func (*NoopSpan) Tag(Tag, string)

type ReportedSpan

type ReportedSpan interface {
	Context() *SegmentContext
	Refs() []*propagation.SpanContext
	StartTime() int64
	EndTime() int64
	OperationName() string
	Peer() string
	SpanType() common.SpanType
	SpanLayer() common.SpanLayer
	IsError() bool
	Tags() []*common.KeyStringValuePair
	Logs() []*v2.Log
	ComponentID() int32
}

ReportedSpan is accessed by Reporter to load reported data

type Reporter

type Reporter interface {
	Register(service string, instance string) (int32, int32, error)
	Send(spans []ReportedSpan)
	Close()
}

Reporter is a data transit specification

type SegmentContext

type SegmentContext struct {
	TraceID         []int64
	SegmentID       []int64
	SpanID          int32
	ParentSpanID    int32
	ParentSegmentID []int64

	FirstSpan Span `json:"-"`
	// contains filtered or unexported fields
}

SegmentContext is the context in a segment

func (SegmentContext) GetReadableGlobalTraceID

func (ctx SegmentContext) GetReadableGlobalTraceID() string

type Span

type Span interface {
	SetOperationName(string)
	GetOperationName() string
	SetPeer(string)
	SetSpanLayer(common.SpanLayer)
	SetComponent(int32)
	Tag(Tag, string)
	Log(time.Time, ...string)
	Error(time.Time, ...string)
	End()
	IsEntry() bool
	IsExit() bool
}

Span interface as common span specification

type SpanOption

type SpanOption func(s *defaultSpan)

SpanOption allows for functional options to adjust behaviour of a Span to be created by CreateLocalSpan

func WithContext

func WithContext(sc *propagation.SpanContext) SpanOption

WithContext setup trace sc from propagation

func WithOperationName added in v1.3.18

func WithOperationName(operationName string) SpanOption

2022-02-22 huangyao WithOperationName setup span OperationName of a span

func WithSpanType

func WithSpanType(spanType SpanType) SpanOption

WithSpanType setup span type of a span

type SpanType

type SpanType int32

SpanType is used to identify entry, exit and local

const (
	// SpanTypeEntry is a entry span, eg http server
	SpanTypeEntry SpanType = 0
	// SpanTypeExit is a exit span, eg http client
	SpanTypeExit SpanType = 1
	// SpanTypeLocal is a local span, eg local method invoke
	SpanTypeLocal SpanType = 2
)

type Tag

type Tag string

Tag are supported by sky-walking engine. As default, all Tags will be stored, but these ones have particular meanings.

const (
	TagURL         Tag = "url"
	TagStatusCode  Tag = "status_code"
	TagHTTPMethod  Tag = "http.method"
	TagDBType      Tag = "db.type"
	TagDBInstance  Tag = "db.instance"
	TagDBStatement Tag = "db.statement"
	//2022-02-22 huangyao 添加sql参数tag常量
	TagDBSqlParameters Tag = "db.sql.parameters"
	TagDBBindVariables Tag = "db.bind_vars"
	TagMQQueue         Tag = "mq.queue"
	TagMQBroker        Tag = "mq.broker"
	TagMQTopic         Tag = "mq.topic"
)

type Tracer

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

Tracer is go2sky tracer implementation.

func NewTracer

func NewTracer(service string, opts ...TracerOption) (tracer *Tracer, err error)

NewTracer return a new go2sky Tracer

Example
package main

import (
	"context"
	"log"
	"time"

	"github.com/powerapm/go2sky"
	"github.com/powerapm/go2sky/reporter"
)

func main() {
	// Use gRPC reporter for production
	r, err := reporter.NewLogReporter()
	if err != nil {
		log.Fatalf("new reporter error %v \n", err)
	}
	defer r.Close()
	tracer, err := go2sky.NewTracer("example", go2sky.WithReporter(r))
	if err != nil {
		log.Fatalf("create tracer error %v \n", err)
	}
	// This for test
	tracer.WaitUntilRegister()
	span, ctx, err := tracer.CreateLocalSpan(context.Background())
	if err != nil {
		log.Fatalf("create new local span error %v \n", err)
	}
	span.SetOperationName("invoke data")
	span.Tag("kind", "outer")
	time.Sleep(time.Second)
	subSpan, _, err := tracer.CreateLocalSpan(ctx)
	if err != nil {
		log.Fatalf("create new sub local span error %v \n", err)
	}
	subSpan.SetOperationName("invoke inner")
	subSpan.Log(time.Now(), "inner", "this is right")
	time.Sleep(time.Second)
	subSpan.End()
	time.Sleep(500 * time.Millisecond)
	span.End()
	time.Sleep(time.Second)
}
Output:

func (*Tracer) CallGoroutineWithContext added in v1.3.19

func (t *Tracer) CallGoroutineWithContext(ctx context.Context) (s Span, nCtx context.Context, err error)

* 2022-04-07 黄尧 针对协程的处理,在协程函数调用一开始

eg:

//ctx为CallGoroutineWithContext()调用之后返回的上下文

go ExcuteAll( ctx,tracer)

//被并发执行的函数,ctx为必传

 func ExcuteAll(ctx context.Context,tracer *go2sky.Tracer ) {
	callSpan, ctx, err := tracer.CallGoroutineWithContext(ctx)
	if err != nil {
		log.Fatalf("CallGoroutineWithContext失败 %v \n", err)
	}
	err = nil
	defer func() {
		if err != nil {
			err = fmt.Errorf("协程执行失败: %s", err.Error())
			callSpan.Error(time.Now(), err.Error())
		}
		callSpan.End()
	}()

	//doSomething
 }

*

func (*Tracer) CreateEntrySpan

func (t *Tracer) CreateEntrySpan(ctx context.Context, operationName string, extractor propagation.Extractor) (s Span, nCtx context.Context, err error)

CreateEntrySpan creates and starts an entry span for incoming request

func (*Tracer) CreateExitSpan

func (t *Tracer) CreateExitSpan(ctx context.Context, operationName string, peer string, injector propagation.Injector) (Span, error)

CreateExitSpan creates and starts an exit span for client

func (*Tracer) CreateExitSpanWithContext added in v1.3.18

func (t *Tracer) CreateExitSpanWithContext(ctx context.Context, operationName string, peer string,
	injector propagation.Injector) (s Span, nCtx context.Context, err error)

CreateExitSpanWithContext creates and starts an exit span for client with context

func (*Tracer) CreateLocalSpan

func (t *Tracer) CreateLocalSpan(ctx context.Context, opts ...SpanOption) (s Span, c context.Context, err error)

CreateLocalSpan creates and starts a span for local usage

func (*Tracer) StartGoroutineWithContext added in v1.3.19

func (t *Tracer) StartGoroutineWithContext(ctx context.Context) (headCtx context.Context, err error)

* 2022-04-07 黄尧 针对协程的处理,在调用协程前进行调用

eg:

//入参:当前上下文,如果没有则传递context.Background()

 ctx, err := tracer.StartGoroutineWithContext(ginCtx.Request.Context())
 if err != nil {
	log.Fatalf("Start Goroutine error: %v", err)
 }

//执行协程,传递相关参数以及返回的上下文

go ExcuteAll(tracer, ctx)

*

func (*Tracer) WaitUntilRegister

func (t *Tracer) WaitUntilRegister()

WaitUntilRegister is a tool helps user to wait until register process has finished

type TracerOption

type TracerOption func(t *Tracer)

TracerOption allows for functional options to adjust behaviour of a Tracer to be created by NewTracer

func WithInstance

func WithInstance(instance string) TracerOption

WithInstance setup instance identify

func WithReporter

func WithReporter(reporter Reporter) TracerOption

WithReporter setup report pipeline for tracer

Directories

Path Synopsis
internal
plugins
gin
Package Gin is a HTTP web framework written in Go (Golang) plugin which can be used for integration with Gin http server.
Package Gin is a HTTP web framework written in Go (Golang) plugin which can be used for integration with Gin http server.
http
Package http contains several client/server http plugin which can be used for integration with net/http.
Package http contains several client/server http plugin which can be used for integration with net/http.
Package propagation holds the required function signatures for Injection and Extraction.
Package propagation holds the required function signatures for Injection and Extraction.
Package reporter holds reporters contain official reporter implementations.
Package reporter holds reporters contain official reporter implementations.
grpc/language-agent-v2/mock_trace
Package mock_language_agent_v2 is a generated GoMock package.
Package mock_language_agent_v2 is a generated GoMock package.
grpc/register/mock_register
Package mock_register is a generated GoMock package.
Package mock_register is a generated GoMock package.
Package go2sky implements a native Apache SkyWalking agent library for Go.
Package go2sky implements a native Apache SkyWalking agent library for Go.

Jump to

Keyboard shortcuts

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