/
tracers.go
70 lines (54 loc) · 1.52 KB
/
tracers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package tracers
import (
"hash/fnv"
"io"
"math"
"math/rand"
"os"
"strconv"
"time"
)
var traceFile *os.File
func init() {
traceFile, _ = os.OpenFile(os.DevNull, os.O_WRONLY, 0644)
rand.Seed(time.Now().UnixNano())
}
func writeTracer(data []byte) error {
n, err := traceFile.Write(data)
if err == nil && n < len(data) {
return io.ErrShortWrite
}
return err
}
func hash(s []byte) uint64 {
h := fnv.New64a()
h.Write(s)
return h.Sum64()
}
func iTou(i int64) uint64 {
return uint64(math.MaxInt64 + i)
}
// Start generates a random span identifier and emits an entry tracer event.
func Start(tag string) (uint64, error) {
spanID := iTou(rand.Int63())
tracer := []byte(">:" + strconv.FormatUint(spanID, 10) + ":" + tag + "::")
err := writeTracer(tracer)
return spanID, err
}
// StartInt emits an entry tracer event using user-specified span identifier.
func StartInt(tag string, spanID uint64) error {
tracer := []byte(">:" + strconv.FormatUint(spanID, 10) + ":" + tag + "::")
return writeTracer(tracer)
}
// StartStr emits an entry tracer event using user-specified span identifier.
func StartStr(tag string, spanID string) (uint64, error) {
intID := hash([]byte(spanID))
tracer := []byte(">:" + strconv.FormatUint(intID, 10) + ":" + tag + "::")
err := writeTracer(tracer)
return intID, err
}
// End emits an exit tracer event for the user-provided span identifier.
func End(tag string, spanID uint64) error {
tracer := []byte("<:" + strconv.FormatUint(spanID, 10) + ":" + tag + "::")
return writeTracer(tracer)
}