This repository has been archived by the owner on Jul 4, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
87 lines (69 loc) · 1.93 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package main
import (
"fmt"
"net/http"
"os"
"time"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/eleven26/zipkin_sampler/sampler"
)
func init() {
log.SetFormatter(&log.JSONFormatter{})
log.SetOutput(os.Stdout)
log.SetLevel(log.WarnLevel)
}
func main() {
cmd := &cobra.Command{
Use: "",
Short: "zipkin sampler",
Long: "zipkin sampler",
Run: func(cmd *cobra.Command, args []string) {
port, _ := cmd.Flags().GetString("port")
endpoint, _ := cmd.Flags().GetString("endpoint")
t, _ := cmd.Flags().GetInt("time")
fmt.Println("listen on port:", port)
fmt.Println("zipkin endpoint:", endpoint)
serveHTTP(port, endpoint, t)
},
Args: cobra.ExactArgs(0),
}
cmd.Flags().StringP("port", "p", "9422", "zipkin sampler port.")
cmd.Flags().StringP("endpoint", "e", "http://192.168.2.168:9411/api/v2/spans", "zipkin collector endpoint.")
cmd.Flags().IntP("time", "t", 5000, "sampling time.")
_ = cmd.MarkFlagRequired("endpoint")
err := cmd.Execute()
if err != nil {
log.Fatal(err)
}
}
func serveHTTP(port, endpoint string, t int) {
reporter := sampler.NewReporter(
endpoint, // zipkin server
sampler.NewTimeBaseSampler(time.Millisecond*time.Duration(t)), // 采集超过指定时间的trace
)
collector := sampler.NewCollector(
time.Minute*10, // 超过 30分钟,没有等到 root trace 就丢弃
reporter,
)
http.HandleFunc("/traces", func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
log.Error("panic error.")
log.Error(err)
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write(([]byte)("panic error."))
}
}()
err := collector.Collect(r.Body)
if err != nil {
log.Error("collect error.")
log.Error(err)
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write(([]byte)("collect error."))
return
}
w.WriteHeader(http.StatusAccepted)
})
log.Fatal(http.ListenAndServe(":"+port, nil))
}