feat: add vendor

This commit is contained in:
fengcaiwen
2023-10-21 20:48:01 +08:00
parent 1c637f45b5
commit 6a6c4e3257
8701 changed files with 2400820 additions and 1 deletions

View File

@@ -0,0 +1 @@
* text eol=lf

26
vendor/github.com/openzipkin/zipkin-go/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,26 @@
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.test
*.prof
.idea

31
vendor/github.com/openzipkin/zipkin-go/.golangci.yml generated vendored Normal file
View File

@@ -0,0 +1,31 @@
run:
deadline: 5m
skip-dirs:
- zipkin_proto3
linters:
disable-all: true
enable:
- dupl
- goconst
- gocyclo
- gofmt
- revive
- govet
- ineffassign
- lll
- misspell
- nakedret
- structcheck
- unparam
- varcheck
linters-settings:
dupl:
threshold: 400
lll:
line-length: 170
gocyclo:
min-complexity: 20
golint:
min-confidence: 0.85

201
vendor/github.com/openzipkin/zipkin-go/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2017 The OpenZipkin 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.

44
vendor/github.com/openzipkin/zipkin-go/Makefile generated vendored Normal file
View File

@@ -0,0 +1,44 @@
# Copyright 2022 The OpenZipkin 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.
.DEFAULT_GOAL := test
.PHONY: test
test:
# MallocNanoZone env var avoids problems in macOS Monterey: golang/go#49138
MallocNanoZone=0 go test -v -race -cover ./...
.PHONY: bench
bench:
go test -v -run - -bench . -benchmem ./...
.PHONY: protoc
protoc:
protoc --go_out=module=github.com/openzipkin/zipkin-go:. proto/zipkin_proto3/zipkin.proto
protoc --go_out=module=github.com/openzipkin/zipkin-go:. proto/testing/*.proto
protoc --go-grpc_out=module=github.com/openzipkin/zipkin-go:. proto/testing/*.proto
.PHONY: lint
lint:
# Ignore grep's exit code since no match returns 1.
echo 'linting...' ; golint ./...
.PHONY: vet
vet:
go vet ./...
.PHONY: all
all: vet lint test bench
.PHONY: example

116
vendor/github.com/openzipkin/zipkin-go/README.md generated vendored Normal file
View File

@@ -0,0 +1,116 @@
<!--
Copyright 2022 The OpenZipkin 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.
-->
# Zipkin Library for Go
[![GHA](https://github.com/openzipkin/zipkin-go/actions/workflows/ci.yml/badge.svg?event=push)](https://github.com/openzipkin/zipkin-go/actions/workflows/ci.yml)
[![codecov](https://codecov.io/gh/openzipkin/zipkin-go/branch/master/graph/badge.svg?token=gXdWofFlsq)](https://codecov.io/gh/openzipkin/zipkin-go)
[![Go Report Card](https://goreportcard.com/badge/github.com/openzipkin/zipkin-go)](https://goreportcard.com/report/github.com/openzipkin/zipkin-go)
[![GoDoc](https://godoc.org/github.com/openzipkin/zipkin-go?status.svg)](https://godoc.org/github.com/openzipkin/zipkin-go)
[![Gitter chat](https://badges.gitter.im/openzipkin/zipkin.svg)](https://gitter.im/openzipkin/zipkin?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Sourcegraph](https://sourcegraph.com/github.com/openzipkin/zipkin-go/-/badge.svg)](https://sourcegraph.com/github.com/openzipkin/zipkin-go?badge)
Zipkin Go is the official Go Tracer / Tracing implementation for Zipkin,
supported by the OpenZipkin community.
## package organization
`zipkin-go` is built with interoperability in mind within the OpenZipkin
community and even 3rd parties, the library consists of several packages.
The main tracing implementation can be found in the root folder of this
repository. Reusable parts not considered core implementation or deemed
beneficiary for usage by others are placed in their own packages within this
repository.
### model
This library implements the Zipkin V2 Span Model which is available in the model
package. It contains a Go data model compatible with the Zipkin V2 API and can
automatically sanitize, parse and (de)serialize to and from the required JSON
representation as used by the official Zipkin V2 Collectors.
### propagation
The propagation package and B3 subpackage hold the logic for propagating
SpanContext (span identifiers and sampling flags) between services participating
in traces. Currently Zipkin B3 Propagation is supported for HTTP and GRPC.
### middleware
The middleware subpackages contain officially supported middleware handlers and
tracing wrappers.
#### http
An easy to use http.Handler middleware for tracing server side requests is
provided. This allows one to use this middleware in applications using
standard library servers as well as most available higher level frameworks. Some
frameworks will have their own instrumentation and middleware that maps better
for their ecosystem.
For HTTP client operations `NewTransport` can return a `http.RoundTripper`
implementation that can either wrap the standard http.Client's Transport or a
custom provided one and add per request tracing. Since HTTP Requests can have
one or multiple redirects it is advisable to always enclose HTTP Client calls
with a `Span` either around the `*http.Client` call level or parent function
level.
For convenience `NewClient` is provided which returns a HTTP Client which embeds
`*http.Client` and provides an `application span` around the HTTP calls when
calling the `DoWithAppSpan()` method.
#### grpc
Easy to use grpc.StatsHandler middleware are provided for tracing gRPC server
and client requests.
For a server, pass `NewServerHandler` when calling `NewServer`, e.g.,
```go
import (
"google.golang.org/grpc"
zipkingrpc "github.com/openzipkin/zipkin-go/middleware/grpc"
)
server = grpc.NewServer(grpc.StatsHandler(zipkingrpc.NewServerHandler(tracer)))
```
For a client, pass `NewClientHandler` when calling `Dial`, e.g.,
```go
import (
"google.golang.org/grpc"
zipkingrpc "github.com/openzipkin/zipkin-go/middleware/grpc"
)
conn, err = grpc.Dial(addr, grpc.WithStatsHandler(zipkingrpc.NewClientHandler(tracer)))
```
### reporter
The reporter package holds the interface which the various Reporter
implementations use. It is exported into its own package as it can be used by
3rd parties to use these Reporter packages in their own libraries for exporting
to the Zipkin ecosystem. The `zipkin-go` tracer also uses the interface to
accept 3rd party Reporter implementations.
#### HTTP Reporter
Most common Reporter type used by Zipkin users transporting Spans to the Zipkin
server using JSON over HTTP. The reporter holds a buffer and reports to the
backend asynchronously.
#### Kafka Reporter
High performance Reporter transporting Spans to the Zipkin server using a Kafka
Producer digesting JSON V2 Spans. The reporter uses the
[Sarama async producer](https://godoc.org/github.com/Shopify/sarama#AsyncProducer)
underneath.
## usage and examples
[HTTP Server Example](examples/httpserver_test.go)

63
vendor/github.com/openzipkin/zipkin-go/context.go generated vendored Normal file
View File

@@ -0,0 +1,63 @@
// Copyright 2022 The OpenZipkin 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.
package zipkin
import (
"context"
"github.com/openzipkin/zipkin-go/model"
)
var defaultNoopSpan = &noopSpan{}
// SpanFromContext retrieves a Zipkin Span from Go's context propagation
// mechanism if found. If not found, returns nil.
func SpanFromContext(ctx context.Context) Span {
if s, ok := ctx.Value(spanKey).(Span); ok {
return s
}
return nil
}
// SpanOrNoopFromContext retrieves a Zipkin Span from Go's context propagation
// mechanism if found. If not found, returns a noopSpan.
// This function typically is used for modules that want to provide existing
// Zipkin spans with additional data, but can't guarantee that spans are
// properly propagated. It is preferred to use SpanFromContext() and test for
// Nil instead of using this function.
func SpanOrNoopFromContext(ctx context.Context) Span {
if s, ok := ctx.Value(spanKey).(Span); ok {
return s
}
return defaultNoopSpan
}
// NewContext stores a Zipkin Span into Go's context propagation mechanism.
func NewContext(ctx context.Context, s Span) context.Context {
return context.WithValue(ctx, spanKey, s)
}
// BaggageFromContext takes a context and returns access to BaggageFields if
// available. Returns nil if there are no BaggageFields found in context.
func BaggageFromContext(ctx context.Context) model.BaggageFields {
if span := SpanFromContext(ctx); span != nil {
return span.Context().Baggage
}
return nil
}
type ctxKey struct{}
var spanKey = ctxKey{}

20
vendor/github.com/openzipkin/zipkin-go/doc.go generated vendored Normal file
View File

@@ -0,0 +1,20 @@
// Copyright 2022 The OpenZipkin 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.
/*
Package zipkin implements a native Zipkin instrumentation library for Go.
See https://zipkin.io for more information about Zipkin.
*/
package zipkin

81
vendor/github.com/openzipkin/zipkin-go/endpoint.go generated vendored Normal file
View File

@@ -0,0 +1,81 @@
// Copyright 2022 The OpenZipkin 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.
package zipkin
import (
"fmt"
"net"
"strconv"
"strings"
"github.com/openzipkin/zipkin-go/model"
)
// NewEndpoint creates a new endpoint given the provided serviceName and
// hostPort.
func NewEndpoint(serviceName string, hostPort string) (*model.Endpoint, error) {
e := &model.Endpoint{
ServiceName: serviceName,
}
if hostPort == "" || hostPort == ":0" {
if serviceName == "" {
// if all properties are empty we should not have an Endpoint object.
return nil, nil
}
return e, nil
}
if strings.IndexByte(hostPort, ':') < 0 {
hostPort += ":0"
}
host, port, err := net.SplitHostPort(hostPort)
if err != nil {
return nil, err
}
p, err := strconv.ParseUint(port, 10, 16)
if err != nil {
return nil, err
}
e.Port = uint16(p)
addrs, err := net.LookupIP(host)
if err != nil {
return nil, fmt.Errorf("host lookup failure: %w", err)
}
for i := range addrs {
addr := addrs[i].To4()
if addr == nil {
// IPv6 - 16 bytes
if e.IPv6 == nil {
e.IPv6 = addrs[i].To16()
}
} else {
// IPv4 - 4 bytes
if e.IPv4 == nil {
e.IPv4 = addr
}
}
if e.IPv4 != nil && e.IPv6 != nil {
// Both IPv4 & IPv6 have been set, done...
break
}
}
return e, nil
}

View File

@@ -0,0 +1,130 @@
// Copyright 2022 The OpenZipkin 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.
/*
Package idgenerator contains several Span and Trace ID generators which can be
used by the Zipkin tracer. Additional third party generators can be plugged in
if they adhere to the IDGenerator interface.
*/
package idgenerator
import (
"math/rand"
"sync"
"time"
"github.com/openzipkin/zipkin-go/model"
)
var (
seededIDGen = rand.New(rand.NewSource(time.Now().UnixNano()))
// NewSource returns a new pseudo-random Source seeded with the given value.
// Unlike the default Source used by top-level functions, this source is not
// safe for concurrent use by multiple goroutines. Hence the need for a mutex.
seededIDLock sync.Mutex
)
// IDGenerator interface can be used to provide the Zipkin Tracer with custom
// implementations to generate Span and Trace IDs.
type IDGenerator interface {
SpanID(traceID model.TraceID) model.ID // Generates a new Span ID
TraceID() model.TraceID // Generates a new Trace ID
}
// NewRandom64 returns an ID Generator which can generate 64 bit trace and span
// id's
func NewRandom64() IDGenerator {
return &randomID64{}
}
// NewRandom128 returns an ID Generator which can generate 128 bit trace and 64
// bit span id's
func NewRandom128() IDGenerator {
return &randomID128{}
}
// NewRandomTimestamped generates 128 bit time sortable traceid's and 64 bit
// spanid's.
func NewRandomTimestamped() IDGenerator {
return &randomTimestamped{}
}
// randomID64 can generate 64 bit traceid's and 64 bit spanid's.
type randomID64 struct{}
func (r *randomID64) TraceID() (id model.TraceID) {
seededIDLock.Lock()
id = model.TraceID{
Low: uint64(seededIDGen.Int63()),
}
seededIDLock.Unlock()
return
}
func (r *randomID64) SpanID(traceID model.TraceID) (id model.ID) {
if !traceID.Empty() {
return model.ID(traceID.Low)
}
seededIDLock.Lock()
id = model.ID(seededIDGen.Int63())
seededIDLock.Unlock()
return
}
// randomID128 can generate 128 bit traceid's and 64 bit spanid's.
type randomID128 struct{}
func (r *randomID128) TraceID() (id model.TraceID) {
seededIDLock.Lock()
id = model.TraceID{
High: uint64(seededIDGen.Int63()),
Low: uint64(seededIDGen.Int63()),
}
seededIDLock.Unlock()
return
}
func (r *randomID128) SpanID(traceID model.TraceID) (id model.ID) {
if !traceID.Empty() {
return model.ID(traceID.Low)
}
seededIDLock.Lock()
id = model.ID(seededIDGen.Int63())
seededIDLock.Unlock()
return
}
// randomTimestamped can generate 128 bit time sortable traceid's compatible
// with AWS X-Ray and 64 bit spanid's.
type randomTimestamped struct{}
func (t *randomTimestamped) TraceID() (id model.TraceID) {
seededIDLock.Lock()
id = model.TraceID{
High: uint64(time.Now().Unix()<<32) + uint64(seededIDGen.Int31()),
Low: uint64(seededIDGen.Int63()),
}
seededIDLock.Unlock()
return
}
func (t *randomTimestamped) SpanID(traceID model.TraceID) (id model.ID) {
if !traceID.Empty() {
return model.ID(traceID.Low)
}
seededIDLock.Lock()
id = model.ID(seededIDGen.Int63())
seededIDLock.Unlock()
return
}

View File

@@ -0,0 +1,60 @@
// Copyright 2022 The OpenZipkin 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.
package model
import (
"encoding/json"
"errors"
"time"
)
// ErrValidTimestampRequired error
var ErrValidTimestampRequired = errors.New("valid annotation timestamp required")
// Annotation associates an event that explains latency with a timestamp.
type Annotation struct {
Timestamp time.Time
Value string
}
// MarshalJSON implements custom JSON encoding
func (a *Annotation) MarshalJSON() ([]byte, error) {
return json.Marshal(&struct {
Timestamp int64 `json:"timestamp"`
Value string `json:"value"`
}{
Timestamp: a.Timestamp.Round(time.Microsecond).UnixNano() / 1e3,
Value: a.Value,
})
}
// UnmarshalJSON implements custom JSON decoding
func (a *Annotation) UnmarshalJSON(b []byte) error {
type Alias Annotation
annotation := &struct {
TimeStamp uint64 `json:"timestamp"`
*Alias
}{
Alias: (*Alias)(a),
}
if err := json.Unmarshal(b, &annotation); err != nil {
return err
}
if annotation.TimeStamp < 1 {
return ErrValidTimestampRequired
}
a.Timestamp = time.Unix(0, int64(annotation.TimeStamp)*1e3)
return nil
}

23
vendor/github.com/openzipkin/zipkin-go/model/doc.go generated vendored Normal file
View File

@@ -0,0 +1,23 @@
// Copyright 2022 The OpenZipkin 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.
/*
Package model contains the Zipkin V2 model which is used by the Zipkin Go
tracer implementation.
Third party instrumentation libraries can use the model and transport packages
found in this Zipkin Go library to directly interface with the Zipkin Server or
Zipkin Collectors without the need to use the tracer implementation itself.
*/
package model

View File

@@ -0,0 +1,50 @@
// Copyright 2022 The OpenZipkin 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.
package model
import (
"encoding/json"
"net"
"strings"
)
// Endpoint holds the network context of a node in the service graph.
type Endpoint struct {
ServiceName string
IPv4 net.IP
IPv6 net.IP
Port uint16
}
// MarshalJSON exports our Endpoint into the correct format for the Zipkin V2 API.
func (e Endpoint) MarshalJSON() ([]byte, error) {
return json.Marshal(&struct {
ServiceName string `json:"serviceName,omitempty"`
IPv4 net.IP `json:"ipv4,omitempty"`
IPv6 net.IP `json:"ipv6,omitempty"`
Port uint16 `json:"port,omitempty"`
}{
strings.ToLower(e.ServiceName),
e.IPv4,
e.IPv6,
e.Port,
})
}
// Empty returns if all Endpoint properties are empty / unspecified.
func (e *Endpoint) Empty() bool {
return e == nil ||
(e.ServiceName == "" && e.Port == 0 && len(e.IPv4) == 0 && len(e.IPv6) == 0)
}

27
vendor/github.com/openzipkin/zipkin-go/model/kind.go generated vendored Normal file
View File

@@ -0,0 +1,27 @@
// Copyright 2022 The OpenZipkin 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.
package model
// Kind clarifies context of timestamp, duration and remoteEndpoint in a span.
type Kind string
// Available Kind values
const (
Undetermined Kind = ""
Client Kind = "CLIENT"
Server Kind = "SERVER"
Producer Kind = "PRODUCER"
Consumer Kind = "CONSUMER"
)

161
vendor/github.com/openzipkin/zipkin-go/model/span.go generated vendored Normal file
View File

@@ -0,0 +1,161 @@
// Copyright 2022 The OpenZipkin 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.
package model
import (
"encoding/json"
"errors"
"strings"
"time"
)
// unmarshal errors
var (
ErrValidTraceIDRequired = errors.New("valid traceId required")
ErrValidIDRequired = errors.New("valid span id required")
ErrValidDurationRequired = errors.New("valid duration required")
)
// BaggageFields holds the interface for consumers needing to interact with
// the fields in application logic.
type BaggageFields interface {
// Get returns the values for a field identified by its key.
Get(key string) []string
// Add adds the provided values to a header designated by key. If not
// accepted by the baggage implementation, it will return false.
Add(key string, value ...string) bool
// Set sets the provided values to a header designated by key. If not
// accepted by the baggage implementation, it will return false.
Set(key string, value ...string) bool
// Delete removes the field data designated by key. If not accepted by the
// baggage implementation, it will return false.
Delete(key string) bool
// Iterate will iterate over the available fields and for each one it will
// trigger the callback function.
Iterate(f func(key string, values []string))
}
// SpanContext holds the context of a Span.
type SpanContext struct {
TraceID TraceID `json:"traceId"`
ID ID `json:"id"`
ParentID *ID `json:"parentId,omitempty"`
Debug bool `json:"debug,omitempty"`
Sampled *bool `json:"-"`
Err error `json:"-"`
Baggage BaggageFields `json:"-"`
}
// SpanModel structure.
//
// If using this library to instrument your application you will not need to
// directly access or modify this representation. The SpanModel is exported for
// use cases involving 3rd party Go instrumentation libraries desiring to
// export data to a Zipkin server using the Zipkin V2 Span model.
type SpanModel struct {
SpanContext
Name string `json:"name,omitempty"`
Kind Kind `json:"kind,omitempty"`
Timestamp time.Time `json:"-"`
Duration time.Duration `json:"-"`
Shared bool `json:"shared,omitempty"`
LocalEndpoint *Endpoint `json:"localEndpoint,omitempty"`
RemoteEndpoint *Endpoint `json:"remoteEndpoint,omitempty"`
Annotations []Annotation `json:"annotations,omitempty"`
Tags map[string]string `json:"tags,omitempty"`
}
// MarshalJSON exports our Model into the correct format for the Zipkin V2 API.
func (s SpanModel) MarshalJSON() ([]byte, error) {
type Alias SpanModel
var timestamp int64
if !s.Timestamp.IsZero() {
if s.Timestamp.Unix() < 1 {
// Zipkin does not allow Timestamps before Unix epoch
return nil, ErrValidTimestampRequired
}
timestamp = s.Timestamp.Round(time.Microsecond).UnixNano() / 1e3
}
if s.Duration < time.Microsecond {
if s.Duration < 0 {
// negative duration is not allowed and signals a timing logic error
return nil, ErrValidDurationRequired
} else if s.Duration > 0 {
// sub microsecond durations are reported as 1 microsecond
s.Duration = 1 * time.Microsecond
}
} else {
// Duration will be rounded to nearest microsecond representation.
//
// NOTE: Duration.Round() is not available in Go 1.8 which we still support.
// To handle microsecond resolution rounding we'll add 500 nanoseconds to
// the duration. When truncated to microseconds in the call to marshal, it
// will be naturally rounded. See TestSpanDurationRounding in span_test.go
s.Duration += 500 * time.Nanosecond
}
s.Name = strings.ToLower(s.Name)
if s.LocalEndpoint.Empty() {
s.LocalEndpoint = nil
}
if s.RemoteEndpoint.Empty() {
s.RemoteEndpoint = nil
}
return json.Marshal(&struct {
T int64 `json:"timestamp,omitempty"`
D int64 `json:"duration,omitempty"`
Alias
}{
T: timestamp,
D: s.Duration.Nanoseconds() / 1e3,
Alias: (Alias)(s),
})
}
// UnmarshalJSON imports our Model from a Zipkin V2 API compatible span
// representation.
func (s *SpanModel) UnmarshalJSON(b []byte) error {
type Alias SpanModel
span := &struct {
T uint64 `json:"timestamp,omitempty"`
D uint64 `json:"duration,omitempty"`
*Alias
}{
Alias: (*Alias)(s),
}
if err := json.Unmarshal(b, &span); err != nil {
return err
}
if s.ID < 1 {
return ErrValidIDRequired
}
if span.T > 0 {
s.Timestamp = time.Unix(0, int64(span.T)*1e3)
}
s.Duration = time.Duration(span.D*1e3) * time.Nanosecond
if s.LocalEndpoint.Empty() {
s.LocalEndpoint = nil
}
if s.RemoteEndpoint.Empty() {
s.RemoteEndpoint = nil
}
return nil
}

View File

@@ -0,0 +1,44 @@
// Copyright 2022 The OpenZipkin 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.
package model
import (
"fmt"
"strconv"
)
// ID type
type ID uint64
// String outputs the 64-bit ID as hex string.
func (i ID) String() string {
return fmt.Sprintf("%016x", uint64(i))
}
// MarshalJSON serializes an ID type (SpanID, ParentSpanID) to HEX.
func (i ID) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf("%q", i.String())), nil
}
// UnmarshalJSON deserializes an ID type (SpanID, ParentSpanID) from HEX.
func (i *ID) UnmarshalJSON(b []byte) (err error) {
var id uint64
if len(b) < 3 {
return nil
}
id, err = strconv.ParseUint(string(b[1:len(b)-1]), 16, 64)
*i = ID(id)
return err
}

View File

@@ -0,0 +1,75 @@
// Copyright 2022 The OpenZipkin 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.
package model
import (
"fmt"
"strconv"
)
// TraceID is a 128 bit number internally stored as 2x uint64 (high & low).
// In case of 64 bit traceIDs, the value can be found in Low.
type TraceID struct {
High uint64
Low uint64
}
// Empty returns if TraceID has zero value.
func (t TraceID) Empty() bool {
return t.Low == 0 && t.High == 0
}
// String outputs the 128-bit traceID as hex string.
func (t TraceID) String() string {
if t.High == 0 {
return fmt.Sprintf("%016x", t.Low)
}
return fmt.Sprintf("%016x%016x", t.High, t.Low)
}
// TraceIDFromHex returns the TraceID from a hex string.
func TraceIDFromHex(h string) (t TraceID, err error) {
if len(h) > 16 {
if t.High, err = strconv.ParseUint(h[0:len(h)-16], 16, 64); err != nil {
return
}
t.Low, err = strconv.ParseUint(h[len(h)-16:], 16, 64)
return
}
t.Low, err = strconv.ParseUint(h, 16, 64)
return
}
// MarshalJSON custom JSON serializer to export the TraceID in the required
// zero padded hex representation.
func (t TraceID) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf("%q", t.String())), nil
}
// UnmarshalJSON custom JSON deserializer to retrieve the traceID from the hex
// encoded representation.
func (t *TraceID) UnmarshalJSON(traceID []byte) error {
if len(traceID) < 3 {
return ErrValidTraceIDRequired
}
// A valid JSON string is encoded wrapped in double quotes. We need to trim
// these before converting the hex payload.
tID, err := TraceIDFromHex(string(traceID[1 : len(traceID)-1]))
if err != nil {
return err
}
*t = tID
return nil
}

48
vendor/github.com/openzipkin/zipkin-go/noop.go generated vendored Normal file
View File

@@ -0,0 +1,48 @@
// Copyright 2022 The OpenZipkin 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.
package zipkin
import (
"time"
"github.com/openzipkin/zipkin-go/model"
)
type noopSpan struct {
model.SpanContext
}
func (n *noopSpan) Context() model.SpanContext { return n.SpanContext }
func (n *noopSpan) SetName(string) {}
func (*noopSpan) SetRemoteEndpoint(*model.Endpoint) {}
func (*noopSpan) Annotate(time.Time, string) {}
func (*noopSpan) Tag(string, string) {}
func (*noopSpan) Finish() {}
func (*noopSpan) FinishedWithDuration(_ time.Duration) {}
func (*noopSpan) Flush() {}
// IsNoop tells whether the span is noop or not. Usually used to avoid resource misusage
// when customizing a span as data won't be recorded
func IsNoop(s Span) bool {
_, ok := s.(*noopSpan)
return ok
}

View File

@@ -0,0 +1,19 @@
// Copyright 2022 The OpenZipkin 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.
/*
Package b3 implements serialization and deserialization logic for Zipkin
B3 Headers.
*/
package b3

View File

@@ -0,0 +1,87 @@
// Copyright 2022 The OpenZipkin 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.
package b3
import (
"google.golang.org/grpc/metadata"
"github.com/openzipkin/zipkin-go/model"
"github.com/openzipkin/zipkin-go/propagation"
)
// ExtractGRPC will extract a span.Context from the gRPC Request metadata if
// found in B3 header format.
func ExtractGRPC(md *metadata.MD) propagation.Extractor {
return func() (*model.SpanContext, error) {
var (
traceIDHeader = GetGRPCHeader(md, TraceID)
spanIDHeader = GetGRPCHeader(md, SpanID)
parentSpanIDHeader = GetGRPCHeader(md, ParentSpanID)
sampledHeader = GetGRPCHeader(md, Sampled)
flagsHeader = GetGRPCHeader(md, Flags)
)
return ParseHeaders(
traceIDHeader, spanIDHeader, parentSpanIDHeader, sampledHeader,
flagsHeader,
)
}
}
// InjectGRPC will inject a span.Context into gRPC metadata.
func InjectGRPC(md *metadata.MD) propagation.Injector {
return func(sc model.SpanContext) error {
if (model.SpanContext{}) == sc {
return ErrEmptyContext
}
if sc.Debug {
setGRPCHeader(md, Flags, "1")
} else if sc.Sampled != nil {
// Debug is encoded as X-B3-Flags: 1. Since Debug implies Sampled,
// we don't send "X-B3-Sampled" if Debug is set.
if *sc.Sampled {
setGRPCHeader(md, Sampled, "1")
} else {
setGRPCHeader(md, Sampled, "0")
}
}
if !sc.TraceID.Empty() && sc.ID > 0 {
// set identifiers
setGRPCHeader(md, TraceID, sc.TraceID.String())
setGRPCHeader(md, SpanID, sc.ID.String())
if sc.ParentID != nil {
setGRPCHeader(md, ParentSpanID, sc.ParentID.String())
}
}
return nil
}
}
// GetGRPCHeader retrieves the last value found for a particular key. If key is
// not found it returns an empty string.
func GetGRPCHeader(md *metadata.MD, key string) string {
v := (*md)[key]
if len(v) < 1 {
return ""
}
return v[len(v)-1]
}
func setGRPCHeader(md *metadata.MD, key, value string) {
(*md)[key] = append((*md)[key], value)
}

View File

@@ -0,0 +1,129 @@
// Copyright 2022 The OpenZipkin 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.
package b3
import (
"net/http"
"github.com/openzipkin/zipkin-go/model"
"github.com/openzipkin/zipkin-go/propagation"
)
// InjectOption provides functional option handler type.
type InjectOption func(opts *InjectOptions)
// InjectOptions provides the available functional options.
type InjectOptions struct {
shouldInjectSingleHeader bool
shouldInjectMultiHeader bool
}
// WithSingleAndMultiHeader allows to include both single and multiple
// headers in the context injection
func WithSingleAndMultiHeader() InjectOption {
return func(opts *InjectOptions) {
opts.shouldInjectSingleHeader = true
opts.shouldInjectMultiHeader = true
}
}
// WithSingleHeaderOnly allows to include only single header in the context
// injection
func WithSingleHeaderOnly() InjectOption {
return func(opts *InjectOptions) {
opts.shouldInjectSingleHeader = true
opts.shouldInjectMultiHeader = false
}
}
// ExtractHTTP will extract a span.Context from the HTTP Request if found in
// B3 header format.
func ExtractHTTP(r *http.Request) propagation.Extractor {
return func() (*model.SpanContext, error) {
var (
traceIDHeader = r.Header.Get(TraceID)
spanIDHeader = r.Header.Get(SpanID)
parentSpanIDHeader = r.Header.Get(ParentSpanID)
sampledHeader = r.Header.Get(Sampled)
flagsHeader = r.Header.Get(Flags)
singleHeader = r.Header.Get(Context)
)
var (
sc *model.SpanContext
sErr error
mErr error
)
if singleHeader != "" {
sc, sErr = ParseSingleHeader(singleHeader)
if sErr == nil {
return sc, nil
}
}
sc, mErr = ParseHeaders(
traceIDHeader, spanIDHeader, parentSpanIDHeader,
sampledHeader, flagsHeader,
)
if mErr != nil && sErr != nil {
return nil, sErr
}
return sc, mErr
}
}
// InjectHTTP will inject a span.Context into a HTTP Request
func InjectHTTP(r *http.Request, opts ...InjectOption) propagation.Injector {
options := InjectOptions{shouldInjectMultiHeader: true}
for _, opt := range opts {
opt(&options)
}
return func(sc model.SpanContext) error {
if (model.SpanContext{}) == sc {
return ErrEmptyContext
}
if options.shouldInjectMultiHeader {
if sc.Debug {
r.Header.Set(Flags, "1")
} else if sc.Sampled != nil {
// Debug is encoded as X-B3-Flags: 1. Since Debug implies Sampled,
// so don't also send "X-B3-Sampled: 1".
if *sc.Sampled {
r.Header.Set(Sampled, "1")
} else {
r.Header.Set(Sampled, "0")
}
}
if !sc.TraceID.Empty() && sc.ID > 0 {
r.Header.Set(TraceID, sc.TraceID.String())
r.Header.Set(SpanID, sc.ID.String())
if sc.ParentID != nil {
r.Header.Set(ParentSpanID, sc.ParentID.String())
}
}
}
if options.shouldInjectSingleHeader {
r.Header.Set(Context, BuildSingleHeader(sc))
}
return nil
}
}

View File

@@ -0,0 +1,101 @@
// Copyright 2022 The OpenZipkin 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.
package b3
import (
"github.com/openzipkin/zipkin-go/model"
"github.com/openzipkin/zipkin-go/propagation"
)
// Map allows serialization and deserialization of SpanContext into a standard Go map.
type Map map[string]string
// Extract implements Extractor
func (m *Map) Extract() (*model.SpanContext, error) {
var (
traceIDHeader = (*m)[TraceID]
spanIDHeader = (*m)[SpanID]
parentSpanIDHeader = (*m)[ParentSpanID]
sampledHeader = (*m)[Sampled]
flagsHeader = (*m)[Flags]
singleHeader = (*m)[Context]
)
var (
sc *model.SpanContext
sErr error
mErr error
)
if singleHeader != "" {
sc, sErr = ParseSingleHeader(singleHeader)
if sErr == nil {
return sc, nil
}
}
sc, mErr = ParseHeaders(
traceIDHeader, spanIDHeader, parentSpanIDHeader,
sampledHeader, flagsHeader,
)
if mErr != nil && sErr != nil {
return nil, sErr
}
return sc, mErr
}
// Inject implements Injector
func (m *Map) Inject(opts ...InjectOption) propagation.Injector {
options := InjectOptions{shouldInjectMultiHeader: true}
for _, opt := range opts {
opt(&options)
}
return func(sc model.SpanContext) error {
if (model.SpanContext{}) == sc {
return ErrEmptyContext
}
if options.shouldInjectMultiHeader {
if sc.Debug {
(*m)[Flags] = "1"
} else if sc.Sampled != nil {
// Debug is encoded as X-B3-Flags: 1. Since Debug implies Sampled,
// so don't also send "X-B3-Sampled: 1".
if *sc.Sampled {
(*m)[Sampled] = "1"
} else {
(*m)[Sampled] = "0"
}
}
if !sc.TraceID.Empty() && sc.ID > 0 {
(*m)[TraceID] = sc.TraceID.String()
(*m)[SpanID] = sc.ID.String()
if sc.ParentID != nil {
(*m)[ParentSpanID] = sc.ParentID.String()
}
}
}
if options.shouldInjectSingleHeader {
(*m)[Context] = BuildSingleHeader(sc)
}
return nil
}
}

View File

@@ -0,0 +1,44 @@
// Copyright 2022 The OpenZipkin 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.
package b3
import "errors"
// Common Header Extraction / Injection errors
var (
ErrInvalidSampledByte = errors.New("invalid B3 Sampled found")
ErrInvalidSampledHeader = errors.New("invalid B3 Sampled header found")
ErrInvalidFlagsHeader = errors.New("invalid B3 Flags header found")
ErrInvalidTraceIDHeader = errors.New("invalid B3 TraceID header found")
ErrInvalidSpanIDHeader = errors.New("invalid B3 SpanID header found")
ErrInvalidParentSpanIDHeader = errors.New("invalid B3 ParentSpanID header found")
ErrInvalidScope = errors.New("require either both TraceID and SpanID or none")
ErrInvalidScopeParent = errors.New("ParentSpanID requires both TraceID and SpanID to be available")
ErrInvalidScopeParentSingle = errors.New("ParentSpanID requires TraceID, SpanID and Sampled to be available")
ErrEmptyContext = errors.New("empty request context")
ErrInvalidTraceIDValue = errors.New("invalid B3 TraceID value found")
ErrInvalidSpanIDValue = errors.New("invalid B3 SpanID value found")
ErrInvalidParentSpanIDValue = errors.New("invalid B3 ParentSpanID value found")
)
// Default B3 Header keys
const (
TraceID = "x-b3-traceid"
SpanID = "x-b3-spanid"
ParentSpanID = "x-b3-parentspanid"
Sampled = "x-b3-sampled"
Flags = "x-b3-flags"
Context = "b3"
)

View File

@@ -0,0 +1,203 @@
// Copyright 2022 The OpenZipkin 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.
package b3
import (
"strconv"
"strings"
"github.com/openzipkin/zipkin-go/model"
)
// ParseHeaders takes values found from B3 Headers and tries to reconstruct a
// SpanContext.
func ParseHeaders(
hdrTraceID, hdrSpanID, hdrParentSpanID, hdrSampled, hdrFlags string,
) (*model.SpanContext, error) {
var (
err error
spanID uint64
requiredCount int
sc = &model.SpanContext{}
)
// correct values for an existing sampled header are "0" and "1".
// For legacy support and being lenient to other tracing implementations we
// allow "true" and "false" as inputs for interop purposes.
switch strings.ToLower(hdrSampled) {
case "0", "false":
sampled := false
sc.Sampled = &sampled
case "1", "true":
sampled := true
sc.Sampled = &sampled
case "":
// sc.Sampled = nil
default:
return nil, ErrInvalidSampledHeader
}
// The only accepted value for Flags is "1". This will set Debug to true. All
// other values and omission of header will be ignored.
if hdrFlags == "1" {
sc.Debug = true
sc.Sampled = nil
}
if hdrTraceID != "" {
requiredCount++
if sc.TraceID, err = model.TraceIDFromHex(hdrTraceID); err != nil {
return nil, ErrInvalidTraceIDHeader
}
}
if hdrSpanID != "" {
requiredCount++
if spanID, err = strconv.ParseUint(hdrSpanID, 16, 64); err != nil {
return nil, ErrInvalidSpanIDHeader
}
sc.ID = model.ID(spanID)
}
if requiredCount != 0 && requiredCount != 2 {
return nil, ErrInvalidScope
}
if hdrParentSpanID != "" {
if requiredCount == 0 {
return nil, ErrInvalidScopeParent
}
if spanID, err = strconv.ParseUint(hdrParentSpanID, 16, 64); err != nil {
return nil, ErrInvalidParentSpanIDHeader
}
parentSpanID := model.ID(spanID)
sc.ParentID = &parentSpanID
}
return sc, nil
}
// ParseSingleHeader takes values found from B3 Single Header and tries to reconstruct a
// SpanContext.
func ParseSingleHeader(contextHeader string) (*model.SpanContext, error) {
if contextHeader == "" {
return nil, ErrEmptyContext
}
var (
sc = model.SpanContext{}
sampling string
)
headerLen := len(contextHeader)
if headerLen == 1 {
sampling = contextHeader
} else if headerLen == 16 || headerLen == 32 {
return nil, ErrInvalidScope
} else if headerLen >= 16+16+1 {
var high, low uint64
pos := 0
if string(contextHeader[16]) != "-" {
// traceID must be 128 bits
var err error
high, err = strconv.ParseUint(contextHeader[0:16], 16, 64)
if err != nil {
return nil, ErrInvalidTraceIDValue
}
pos = 16
}
low, err := strconv.ParseUint(contextHeader[pos:pos+16], 16, 64)
if err != nil {
return nil, ErrInvalidTraceIDValue
}
sc.TraceID = model.TraceID{High: high, Low: low}
rawID, err := strconv.ParseUint(contextHeader[pos+16+1:pos+16+1+16], 16, 64)
if err != nil {
return nil, ErrInvalidSpanIDValue
}
sc.ID = model.ID(rawID)
if headerLen > pos+16+1+16 {
if headerLen == pos+16+1+16+1 {
return nil, ErrInvalidSampledByte
}
if headerLen == pos+16+1+16+1+1 {
sampling = string(contextHeader[pos+16+1+16+1])
} else if headerLen == pos+16+1+16+1+16 {
return nil, ErrInvalidScopeParentSingle
} else if headerLen == pos+16+1+16+1+1+1+16 {
sampling = string(contextHeader[pos+16+1+16+1])
var rawParentID uint64
rawParentID, err = strconv.ParseUint(contextHeader[pos+16+1+16+1+1+1:], 16, 64)
if err != nil {
return nil, ErrInvalidParentSpanIDValue
}
parentID := model.ID(rawParentID)
sc.ParentID = &parentID
} else {
return nil, ErrInvalidParentSpanIDValue
}
}
} else {
return nil, ErrInvalidTraceIDValue
}
switch sampling {
case "d":
sc.Debug = true
case "1":
trueVal := true
sc.Sampled = &trueVal
case "0":
falseVal := false
sc.Sampled = &falseVal
case "":
default:
return nil, ErrInvalidSampledByte
}
return &sc, nil
}
// BuildSingleHeader takes the values from the SpanContext and builds the B3 header
func BuildSingleHeader(sc model.SpanContext) string {
var header []string
if !sc.TraceID.Empty() && sc.ID > 0 {
header = append(header, sc.TraceID.String(), sc.ID.String())
}
if sc.Debug {
header = append(header, "d")
} else if sc.Sampled != nil {
if *sc.Sampled {
header = append(header, "1")
} else {
header = append(header, "0")
}
}
if sc.ParentID != nil {
header = append(header, sc.ParentID.String())
}
return strings.Join(header, "-")
}

View File

@@ -0,0 +1,30 @@
// Copyright 2022 The OpenZipkin 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.
/*
Package propagation holds the required function signatures for Injection and
Extraction as used by the Zipkin Tracer.
Subpackages of this package contain officially supported standard propagation
implementations.
*/
package propagation
import "github.com/openzipkin/zipkin-go/model"
// Extractor function signature
type Extractor func() (*model.SpanContext, error)
// Injector function signature
type Injector func(model.SpanContext) error

View File

@@ -0,0 +1,275 @@
// Copyright 2022 The OpenZipkin 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.
/*
Package http implements a HTTP reporter to send spans to Zipkin V2 collectors.
*/
package http
import (
"bytes"
"context"
"log"
"net/http"
"os"
"sync"
"time"
"github.com/openzipkin/zipkin-go/model"
"github.com/openzipkin/zipkin-go/reporter"
)
// defaults
const (
defaultTimeout = 5 * time.Second // timeout for http request in seconds
defaultBatchInterval = 1 * time.Second // BatchInterval in seconds
defaultBatchSize = 100
defaultMaxBacklog = 1000
)
// HTTPDoer will do a request to the Zipkin HTTP Collector
type HTTPDoer interface { // nolint: revive // keep as is, we don't want to break dependendants
Do(req *http.Request) (*http.Response, error)
}
// httpReporter will send spans to a Zipkin HTTP Collector using Zipkin V2 API.
type httpReporter struct {
url string
client HTTPDoer
logger *log.Logger
batchInterval time.Duration
batchSize int
maxBacklog int
batchMtx *sync.Mutex
batch []*model.SpanModel
spanC chan *model.SpanModel
sendC chan struct{}
quit chan struct{}
shutdown chan error
reqCallback RequestCallbackFn
reqTimeout time.Duration
serializer reporter.SpanSerializer
}
// Send implements reporter
func (r *httpReporter) Send(s model.SpanModel) {
r.spanC <- &s
}
// Close implements reporter
func (r *httpReporter) Close() error {
close(r.quit)
return <-r.shutdown
}
func (r *httpReporter) loop() {
var (
nextSend = time.Now().Add(r.batchInterval)
ticker = time.NewTicker(r.batchInterval / 10)
tickerChan = ticker.C
)
defer ticker.Stop()
for {
select {
case span := <-r.spanC:
currentBatchSize := r.append(span)
if currentBatchSize >= r.batchSize {
nextSend = time.Now().Add(r.batchInterval)
r.enqueueSend()
}
case <-tickerChan:
if time.Now().After(nextSend) {
nextSend = time.Now().Add(r.batchInterval)
r.enqueueSend()
}
case <-r.quit:
close(r.sendC)
return
}
}
}
func (r *httpReporter) sendLoop() {
for range r.sendC {
_ = r.sendBatch()
}
r.shutdown <- r.sendBatch()
}
func (r *httpReporter) enqueueSend() {
select {
case r.sendC <- struct{}{}:
default:
// Do nothing if there's a pending send request already
}
}
func (r *httpReporter) append(span *model.SpanModel) (newBatchSize int) {
r.batchMtx.Lock()
r.batch = append(r.batch, span)
if len(r.batch) > r.maxBacklog {
dispose := len(r.batch) - r.maxBacklog
r.logger.Printf("backlog too long, disposing %d spans", dispose)
r.batch = r.batch[dispose:]
}
newBatchSize = len(r.batch)
r.batchMtx.Unlock()
return
}
func (r *httpReporter) sendBatch() error {
// Select all current spans in the batch to be sent
r.batchMtx.Lock()
sendBatch := r.batch[:]
r.batchMtx.Unlock()
if len(sendBatch) == 0 {
return nil
}
body, err := r.serializer.Serialize(sendBatch)
if err != nil {
r.logger.Printf("failed when marshalling the spans batch: %s\n", err.Error())
return err
}
req, err := http.NewRequest("POST", r.url, bytes.NewReader(body))
if err != nil {
r.logger.Printf("failed when creating the request: %s\n", err.Error())
return err
}
// By default we send b3:0 header to mitigate trace reporting amplification in
// service mesh environments where the sidecar proxies might trace the call
// we do here towards the Zipkin collector.
req.Header.Set("b3", "0")
req.Header.Set("Content-Type", r.serializer.ContentType())
if r.reqCallback != nil {
r.reqCallback(req)
}
ctx, cancel := context.WithTimeout(req.Context(), r.reqTimeout)
defer cancel()
resp, err := r.client.Do(req.WithContext(ctx))
if err != nil {
r.logger.Printf("failed to send the request: %s\n", err.Error())
return err
}
_ = resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
r.logger.Printf("failed the request with status code %d\n", resp.StatusCode)
}
// Remove sent spans from the batch even if they were not saved
r.batchMtx.Lock()
r.batch = r.batch[len(sendBatch):]
r.batchMtx.Unlock()
return nil
}
// RequestCallbackFn receives the initialized request from the Collector before
// sending it over the wire. This allows one to plug in additional headers or
// do other customization.
type RequestCallbackFn func(*http.Request)
// ReporterOption sets a parameter for the HTTP Reporter
type ReporterOption func(r *httpReporter)
// Timeout sets maximum timeout for the http request through its context.
func Timeout(duration time.Duration) ReporterOption {
return func(r *httpReporter) { r.reqTimeout = duration }
}
// BatchSize sets the maximum batch size, after which a collect will be
// triggered. The default batch size is 100 traces.
func BatchSize(n int) ReporterOption {
return func(r *httpReporter) { r.batchSize = n }
}
// MaxBacklog sets the maximum backlog size. When batch size reaches this
// threshold, spans from the beginning of the batch will be disposed.
func MaxBacklog(n int) ReporterOption {
return func(r *httpReporter) { r.maxBacklog = n }
}
// BatchInterval sets the maximum duration we will buffer traces before
// emitting them to the collector. The default batch interval is 1 second.
func BatchInterval(d time.Duration) ReporterOption {
return func(r *httpReporter) { r.batchInterval = d }
}
// Client sets a custom http client to use under the interface HTTPDoer
// which includes a `Do` method with same signature as the *http.Client
func Client(client HTTPDoer) ReporterOption {
return func(r *httpReporter) { r.client = client }
}
// RequestCallback registers a callback function to adjust the reporter
// *http.Request before it sends the request to Zipkin.
func RequestCallback(rc RequestCallbackFn) ReporterOption {
return func(r *httpReporter) { r.reqCallback = rc }
}
// Logger sets the logger used to report errors in the collection
// process.
func Logger(l *log.Logger) ReporterOption {
return func(r *httpReporter) { r.logger = l }
}
// Serializer sets the serialization function to use for sending span data to
// Zipkin.
func Serializer(serializer reporter.SpanSerializer) ReporterOption {
return func(r *httpReporter) {
if serializer != nil {
r.serializer = serializer
}
}
}
// NewReporter returns a new HTTP Reporter.
// url should be the endpoint to send the spans to, e.g.
// http://localhost:9411/api/v2/spans
func NewReporter(url string, opts ...ReporterOption) reporter.Reporter {
r := httpReporter{
url: url,
logger: log.New(os.Stderr, "", log.LstdFlags),
client: &http.Client{},
batchInterval: defaultBatchInterval,
batchSize: defaultBatchSize,
maxBacklog: defaultMaxBacklog,
batch: []*model.SpanModel{},
spanC: make(chan *model.SpanModel),
sendC: make(chan struct{}, 1),
quit: make(chan struct{}, 1),
shutdown: make(chan error, 1),
batchMtx: &sync.Mutex{},
serializer: reporter.JSONSerializer{},
reqTimeout: defaultTimeout,
}
for _, opt := range opts {
opt(&r)
}
go r.loop()
go r.sendLoop()
return &r
}

View File

@@ -0,0 +1,41 @@
// Copyright 2022 The OpenZipkin 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.
/*
Package reporter holds the Reporter interface which is used by the Zipkin
Tracer to send finished spans.
Subpackages of package reporter contain officially supported standard
reporter implementations.
*/
package reporter
import "github.com/openzipkin/zipkin-go/model"
// Reporter interface can be used to provide the Zipkin Tracer with custom
// implementations to publish Zipkin Span data.
type Reporter interface {
Send(model.SpanModel) // Send Span data to the reporter
Close() error // Close the reporter
}
type noopReporter struct{}
func (r *noopReporter) Send(model.SpanModel) {}
func (r *noopReporter) Close() error { return nil }
// NewNoopReporter returns a no-op Reporter implementation.
func NewNoopReporter() Reporter {
return &noopReporter{}
}

View File

@@ -0,0 +1,42 @@
// Copyright 2022 The OpenZipkin 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.
package reporter
import (
"encoding/json"
"github.com/openzipkin/zipkin-go/model"
)
// SpanSerializer describes the methods needed for allowing to set Span encoding
// type for the various Zipkin transports.
type SpanSerializer interface {
Serialize([]*model.SpanModel) ([]byte, error)
ContentType() string
}
// JSONSerializer implements the default JSON encoding SpanSerializer.
type JSONSerializer struct{}
// Serialize takes an array of Zipkin SpanModel objects and returns a JSON
// encoding of it.
func (JSONSerializer) Serialize(spans []*model.SpanModel) ([]byte, error) {
return json.Marshal(spans)
}
// ContentType returns the ContentType needed for this encoding.
func (JSONSerializer) ContentType() string {
return "application/json"
}

127
vendor/github.com/openzipkin/zipkin-go/sample.go generated vendored Normal file
View File

@@ -0,0 +1,127 @@
// Copyright 2022 The OpenZipkin 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.
package zipkin
import (
"fmt"
"math"
"math/rand"
"sync"
"time"
)
// Sampler functions return if a Zipkin span should be sampled, based on its
// traceID.
type Sampler func(id uint64) bool
// NeverSample will always return false. If used by a service it will not allow
// the service to start traces but will still allow the service to participate
// in traces started upstream.
func NeverSample(_ uint64) bool { return false }
// AlwaysSample will always return true. If used by a service it will always start
// traces if no upstream trace has been propagated. If an incoming upstream trace
// is not sampled the service will adhere to this and only propagate the context.
func AlwaysSample(_ uint64) bool { return true }
// NewModuloSampler provides a generic type Sampler.
func NewModuloSampler(mod uint64) Sampler {
if mod < 2 {
return AlwaysSample
}
return func(id uint64) bool {
return (id % mod) == 0
}
}
// NewBoundarySampler is appropriate for high-traffic instrumentation who
// provision random trace ids, and make the sampling decision only once.
// It defends against nodes in the cluster selecting exactly the same ids.
func NewBoundarySampler(rate float64, salt int64) (Sampler, error) {
if rate == 0.0 {
return NeverSample, nil
}
if rate == 1.0 {
return AlwaysSample, nil
}
if rate < 0.0001 || rate > 1 {
return nil, fmt.Errorf("rate should be 0.0 or between 0.0001 and 1: was %f", rate)
}
var (
boundary = int64(rate * 10000)
usalt = uint64(salt)
)
return func(id uint64) bool {
return int64(math.Abs(float64(id^usalt)))%10000 < boundary
}, nil
}
// NewCountingSampler is appropriate for low-traffic instrumentation or
// those who do not provision random trace ids. It is not appropriate for
// collectors as the sampling decision isn't idempotent (consistent based
// on trace id).
func NewCountingSampler(rate float64) (Sampler, error) {
if rate == 0.0 {
return NeverSample, nil
}
if rate == 1.0 {
return AlwaysSample, nil
}
if rate < 0.01 || rate > 1 {
return nil, fmt.Errorf("rate should be 0.0 or between 0.01 and 1: was %f", rate)
}
var (
i = 0
outOf100 = int(rate*100 + math.Copysign(0.5, rate*100)) // for rounding float to int conversion instead of truncation
decisions = randomBitSet(100, outOf100, rand.New(rand.NewSource(time.Now().UnixNano())))
mtx = &sync.Mutex{}
)
return func(_ uint64) bool {
mtx.Lock()
result := decisions[i]
i++
if i == 100 {
i = 0
}
mtx.Unlock()
return result
}, nil
}
/**
* Reservoir sampling algorithm borrowed from Stack Overflow.
*
* http://stackoverflow.com/questions/12817946/generate-a-random-bitset-with-n-1s
*/
func randomBitSet(size int, cardinality int, rnd *rand.Rand) []bool {
result := make([]bool, size)
chosen := make([]int, cardinality)
var i int
for i = 0; i < cardinality; i++ {
chosen[i] = i
result[i] = true
}
for ; i < size; i++ {
j := rnd.Intn(i + 1)
if j < cardinality {
result[chosen[j]] = false
result[i] = true
chosen[j] = i
}
}
return result
}

58
vendor/github.com/openzipkin/zipkin-go/span.go generated vendored Normal file
View File

@@ -0,0 +1,58 @@
// Copyright 2022 The OpenZipkin 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.
package zipkin
import (
"time"
"github.com/openzipkin/zipkin-go/model"
)
// Span interface as returned by Tracer.StartSpan()
type Span interface {
// Context returns the Span's SpanContext.
Context() model.SpanContext
// SetName updates the Span's name.
SetName(string)
// SetRemoteEndpoint updates the Span's Remote Endpoint.
SetRemoteEndpoint(*model.Endpoint)
// Annotate adds a timed event to the Span.
Annotate(time.Time, string)
// Tag sets Tag with given key and value to the Span. If key already exists in
// the Span the value will be overridden except for error tags where the first
// value is persisted.
Tag(string, string)
// Finish the Span and send to Reporter. If DelaySend option was used at
// Span creation time, Finish will not send the Span to the Reporter. It then
// becomes the user's responsibility to get the Span reported (by using
// span.Flush).
Finish()
// Finish the Span with duration and send to Reporter. If DelaySend option was used at
// Span creation time, FinishedWithDuration will not send the Span to the Reporter. It then
// becomes the user's responsibility to get the Span reported (by using
// span.Flush).
FinishedWithDuration(duration time.Duration)
// Flush the Span to the Reporter (regardless of being finished or not).
// This can be used if the DelaySend SpanOption was set or when dealing with
// one-way RPC tracing where duration might not be measured.
Flush()
}

View File

@@ -0,0 +1,101 @@
// Copyright 2022 The OpenZipkin 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.
package zipkin
import (
"sync"
"sync/atomic"
"time"
"github.com/openzipkin/zipkin-go/model"
)
type spanImpl struct {
mtx sync.RWMutex
model.SpanModel
tracer *Tracer
mustCollect int32 // used as atomic bool (1 = true, 0 = false)
flushOnFinish bool
}
func (s *spanImpl) Context() model.SpanContext {
return s.SpanContext
}
func (s *spanImpl) SetName(name string) {
s.mtx.Lock()
s.Name = name
s.mtx.Unlock()
}
func (s *spanImpl) SetRemoteEndpoint(e *model.Endpoint) {
s.mtx.Lock()
if e == nil {
s.RemoteEndpoint = nil
} else {
s.RemoteEndpoint = &model.Endpoint{}
*s.RemoteEndpoint = *e
}
s.mtx.Unlock()
}
func (s *spanImpl) Annotate(t time.Time, value string) {
a := model.Annotation{
Timestamp: t,
Value: value,
}
s.mtx.Lock()
s.Annotations = append(s.Annotations, a)
s.mtx.Unlock()
}
func (s *spanImpl) Tag(key, value string) {
s.mtx.Lock()
if key == string(TagError) {
if _, found := s.Tags[key]; found {
s.mtx.Unlock()
return
}
}
s.Tags[key] = value
s.mtx.Unlock()
}
func (s *spanImpl) Finish() {
if atomic.CompareAndSwapInt32(&s.mustCollect, 1, 0) {
s.Duration = time.Since(s.Timestamp)
if s.flushOnFinish {
s.tracer.reporter.Send(s.SpanModel)
}
}
}
func (s *spanImpl) FinishedWithDuration(d time.Duration) {
if atomic.CompareAndSwapInt32(&s.mustCollect, 1, 0) {
s.Duration = d
if s.flushOnFinish {
s.tracer.reporter.Send(s.SpanModel)
}
}
}
func (s *spanImpl) Flush() {
if s.SpanModel.Debug || (s.SpanModel.Sampled != nil && *s.SpanModel.Sampled) {
s.tracer.reporter.Send(s.SpanModel)
}
}

88
vendor/github.com/openzipkin/zipkin-go/span_options.go generated vendored Normal file
View File

@@ -0,0 +1,88 @@
// Copyright 2022 The OpenZipkin 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.
package zipkin
import (
"time"
"github.com/openzipkin/zipkin-go/model"
)
// SpanOption allows for functional options to adjust behavior and payload of
// the Span to be created with tracer.StartSpan().
type SpanOption func(t *Tracer, s *spanImpl)
// Kind sets the kind of the span being created.
func Kind(kind model.Kind) SpanOption {
return func(t *Tracer, s *spanImpl) {
s.Kind = kind
}
}
// Parent will use provided SpanContext as parent to the span being created.
func Parent(sc model.SpanContext) SpanOption {
return func(t *Tracer, s *spanImpl) {
if sc.Err != nil {
// encountered an extraction error
switch t.extractFailurePolicy {
case ExtractFailurePolicyRestart:
case ExtractFailurePolicyError:
panic(s.SpanContext.Err)
case ExtractFailurePolicyTagAndRestart:
s.Tags["error.extract"] = sc.Err.Error()
default:
panic(ErrInvalidExtractFailurePolicy)
}
/* don't use provided SpanContext, but restart trace */
return
}
s.SpanContext = sc
}
}
// StartTime uses a given start time for the span being created.
func StartTime(start time.Time) SpanOption {
return func(t *Tracer, s *spanImpl) {
s.Timestamp = start
}
}
// RemoteEndpoint sets the remote endpoint of the span being created.
func RemoteEndpoint(e *model.Endpoint) SpanOption {
return func(t *Tracer, s *spanImpl) {
s.RemoteEndpoint = e
}
}
// Tags sets initial tags for the span being created. If default tracer tags
// are present they will be overwritten on key collisions.
func Tags(tags map[string]string) SpanOption {
return func(t *Tracer, s *spanImpl) {
for k, v := range tags {
s.Tags[k] = v
}
}
}
// FlushOnFinish when set to false will disable span.Finish() to send the Span
// to the Reporter automatically (which is the default behavior). If set to
// false, having the Span be reported becomes the responsibility of the user.
// This is available if late tag data is expected to be only available after the
// required finish time of the Span.
func FlushOnFinish(b bool) SpanOption {
return func(t *Tracer, s *spanImpl) {
s.flushOnFinish = b
}
}

37
vendor/github.com/openzipkin/zipkin-go/tags.go generated vendored Normal file
View File

@@ -0,0 +1,37 @@
// Copyright 2022 The OpenZipkin 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.
package zipkin
// Tag holds available types
type Tag string
// Common Tag values
const (
TagHTTPMethod Tag = "http.method"
TagHTTPPath Tag = "http.path"
TagHTTPUrl Tag = "http.url"
TagHTTPRoute Tag = "http.route"
TagHTTPStatusCode Tag = "http.status_code"
TagHTTPRequestSize Tag = "http.request.size"
TagHTTPResponseSize Tag = "http.response.size"
TagGRPCStatusCode Tag = "grpc.status_code"
TagSQLQuery Tag = "sql.query"
TagError Tag = "error"
)
// Set a standard Tag with a payload on provided Span.
func (t Tag) Set(s Span, value string) {
s.Tag(string(t), value)
}

200
vendor/github.com/openzipkin/zipkin-go/tracer.go generated vendored Normal file
View File

@@ -0,0 +1,200 @@
// Copyright 2022 The OpenZipkin 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.
package zipkin
import (
"context"
"sync/atomic"
"time"
"github.com/openzipkin/zipkin-go/idgenerator"
"github.com/openzipkin/zipkin-go/model"
"github.com/openzipkin/zipkin-go/propagation"
"github.com/openzipkin/zipkin-go/reporter"
)
// Tracer is our Zipkin tracer implementation. It should be initialized using
// the NewTracer method.
type Tracer struct {
defaultTags map[string]string
extractFailurePolicy ExtractFailurePolicy
sampler Sampler
generate idgenerator.IDGenerator
reporter reporter.Reporter
localEndpoint *model.Endpoint
noop int32 // used as atomic bool (1 = true, 0 = false)
sharedSpans bool
unsampledNoop bool
}
// NewTracer returns a new Zipkin Tracer.
func NewTracer(rep reporter.Reporter, opts ...TracerOption) (*Tracer, error) {
// set default tracer options
t := &Tracer{
defaultTags: make(map[string]string),
extractFailurePolicy: ExtractFailurePolicyRestart,
sampler: AlwaysSample,
generate: idgenerator.NewRandom64(),
reporter: rep,
localEndpoint: nil,
noop: 0,
sharedSpans: true,
unsampledNoop: false,
}
// if no reporter was provided we default to noop implementation.
if t.reporter == nil {
t.reporter = reporter.NewNoopReporter()
t.noop = 1
}
// process functional options
for _, opt := range opts {
if err := opt(t); err != nil {
return nil, err
}
}
return t, nil
}
// StartSpanFromContext creates and starts a span using the span found in
// context as parent. If no parent span is found a root span is created.
func (t *Tracer) StartSpanFromContext(ctx context.Context, name string, options ...SpanOption) (Span, context.Context) {
if parentSpan := SpanFromContext(ctx); parentSpan != nil {
options = append(options, Parent(parentSpan.Context()))
}
span := t.StartSpan(name, options...)
return span, NewContext(ctx, span)
}
// StartSpan creates and starts a span.
func (t *Tracer) StartSpan(name string, options ...SpanOption) Span {
if atomic.LoadInt32(&t.noop) == 1 {
// even though we're going to return a noopSpan, we need to initialize
// a spanImpl to fetch the parent context that might be provided as a
// SpanOption
s := &spanImpl{
SpanModel: model.SpanModel{
Tags: make(map[string]string),
},
}
for _, option := range options {
option(t, s)
}
// return noopSpan with the extracted SpanContext from spanImpl.
return &noopSpan{SpanContext: s.SpanContext}
}
s := &spanImpl{
SpanModel: model.SpanModel{
Kind: model.Undetermined,
Name: name,
LocalEndpoint: t.localEndpoint,
Annotations: make([]model.Annotation, 0),
Tags: make(map[string]string),
},
flushOnFinish: true,
tracer: t,
}
// add default tracer tags to span
for k, v := range t.defaultTags {
s.Tag(k, v)
}
// handle provided functional options
for _, option := range options {
option(t, s)
}
if s.TraceID.Empty() {
// create root span
s.SpanContext.TraceID = t.generate.TraceID()
s.SpanContext.ID = t.generate.SpanID(s.SpanContext.TraceID)
} else {
// valid parent context found
if t.sharedSpans && s.Kind == model.Server {
// join span
s.Shared = true
} else {
// regular child span
parentID := s.SpanContext.ID
s.SpanContext.ParentID = &parentID
s.SpanContext.ID = t.generate.SpanID(model.TraceID{})
}
}
if !s.SpanContext.Debug && s.Sampled == nil {
// deferred sampled context found, invoke sampler
sampled := t.sampler(s.SpanContext.TraceID.Low)
s.SpanContext.Sampled = &sampled
if sampled {
s.mustCollect = 1
}
} else {
if s.SpanContext.Debug || *s.Sampled {
s.mustCollect = 1
}
}
if t.unsampledNoop && s.mustCollect == 0 {
// trace not being sampled and noop requested
return &noopSpan{
SpanContext: s.SpanContext,
}
}
// add start time
if s.Timestamp.IsZero() {
s.Timestamp = time.Now()
}
return s
}
// Extract extracts a SpanContext using the provided Extractor function.
func (t *Tracer) Extract(extractor propagation.Extractor) (sc model.SpanContext) {
if atomic.LoadInt32(&t.noop) == 1 {
return
}
psc, err := extractor()
if psc != nil {
sc = *psc
}
sc.Err = err
return
}
// SetNoop allows for killswitch behavior. If set to true the tracer will return
// noopSpans and all data is dropped. This allows operators to stop tracing in
// risk scenarios. Set back to false to resume tracing.
func (t *Tracer) SetNoop(noop bool) {
if noop {
atomic.CompareAndSwapInt32(&t.noop, 0, 1)
} else {
atomic.CompareAndSwapInt32(&t.noop, 1, 0)
}
}
// LocalEndpoint returns a copy of the currently set local endpoint of the
// tracer instance.
func (t *Tracer) LocalEndpoint() *model.Endpoint {
if t.localEndpoint == nil {
return nil
}
ep := *t.localEndpoint
return &ep
}

View File

@@ -0,0 +1,138 @@
// Copyright 2022 The OpenZipkin 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.
package zipkin
import (
"errors"
"github.com/openzipkin/zipkin-go/idgenerator"
"github.com/openzipkin/zipkin-go/model"
)
// Tracer Option Errors
var (
ErrInvalidEndpoint = errors.New("requires valid local endpoint")
ErrInvalidExtractFailurePolicy = errors.New("invalid extract failure policy provided")
)
// ExtractFailurePolicy deals with Extraction errors
type ExtractFailurePolicy int
// ExtractFailurePolicyOptions
const (
ExtractFailurePolicyRestart ExtractFailurePolicy = iota
ExtractFailurePolicyError
ExtractFailurePolicyTagAndRestart
)
// TracerOption allows for functional options to adjust behavior of the Tracer
// to be created with NewTracer().
type TracerOption func(o *Tracer) error
// WithLocalEndpoint sets the local endpoint of the tracer.
func WithLocalEndpoint(e *model.Endpoint) TracerOption {
return func(o *Tracer) error {
if e == nil {
o.localEndpoint = nil
return nil
}
ep := *e
o.localEndpoint = &ep
return nil
}
}
// WithExtractFailurePolicy allows one to set the ExtractFailurePolicy.
func WithExtractFailurePolicy(p ExtractFailurePolicy) TracerOption {
return func(o *Tracer) error {
if p < 0 || p > ExtractFailurePolicyTagAndRestart {
return ErrInvalidExtractFailurePolicy
}
o.extractFailurePolicy = p
return nil
}
}
// WithNoopSpan if set to true will switch to a NoopSpan implementation
// if the trace is not sampled.
func WithNoopSpan(unsampledNoop bool) TracerOption {
return func(o *Tracer) error {
o.unsampledNoop = unsampledNoop
return nil
}
}
// WithSharedSpans allows to place client-side and server-side annotations
// for a RPC call in the same span (Zipkin V1 behavior) or different spans
// (more in line with other tracing solutions). By default this Tracer
// uses shared host spans (so client-side and server-side in the same span).
func WithSharedSpans(val bool) TracerOption {
return func(o *Tracer) error {
o.sharedSpans = val
return nil
}
}
// WithSampler allows one to set a Sampler function
func WithSampler(sampler Sampler) TracerOption {
return func(o *Tracer) error {
o.sampler = sampler
return nil
}
}
// WithTraceID128Bit if set to true will instruct the Tracer to start traces
// with 128 bit TraceID's. If set to false the Tracer will start traces with
// 64 bits.
func WithTraceID128Bit(val bool) TracerOption {
return func(o *Tracer) error {
if val {
o.generate = idgenerator.NewRandom128()
} else {
o.generate = idgenerator.NewRandom64()
}
return nil
}
}
// WithIDGenerator allows one to set a custom ID Generator
func WithIDGenerator(generator idgenerator.IDGenerator) TracerOption {
return func(o *Tracer) error {
o.generate = generator
return nil
}
}
// WithTags allows one to set default tags to be added to each created span
func WithTags(tags map[string]string) TracerOption {
return func(o *Tracer) error {
for k, v := range tags {
o.defaultTags[k] = v
}
return nil
}
}
// WithNoopTracer allows one to start the Tracer as Noop implementation.
func WithNoopTracer(tracerNoop bool) TracerOption {
return func(o *Tracer) error {
if tracerNoop {
o.noop = 1
} else {
o.noop = 0
}
return nil
}
}