-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
112 lines (96 loc) · 2.64 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package main
import (
"encoding/json"
"flag"
"fmt"
"net/http"
"strconv"
"go.searchlight.dev/prometheus-metrics-exporter/metrics"
"github.com/golang/glog"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/prometheus/prompb"
"github.com/spf13/cobra"
)
var (
alertMetrc = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "alert_test",
Help: "for testing alert purpose",
ConstLabels: prometheus.Labels{
"app": "metric-exporter",
},
})
)
func NewRootCmd() *cobra.Command {
metricsConf := metrics.NewMetricsExporterConfigs()
var parallelProcess int
var rootCmd = &cobra.Command{
Use: "metrics-writer [command]",
Short: `Prometheus metrics writer`,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
if err := metricsConf.Validate(); err != nil {
return err
}
if parallelProcess < 1 {
parallelProcess = 1
}
stopCh := make(chan struct{})
for i := 1; i <= parallelProcess; i++ {
metricsExporter, err := metrics.NewMetricsExporter(metricsConf, prometheus.NewRegistry())
if err != nil {
return errors.Wrap(err, "failed to create client for metrics exporter")
}
alertMetrc.Set(0)
metricsExporter.Register(alertMetrc)
metricsExporter.Register(prometheus.NewGoCollector())
metricsExporter.Register(prometheus.NewProcessCollector(prometheus.ProcessCollectorOpts{}))
lbs := []prompb.Label{
{
Value: strconv.Itoa(i),
Name: "extra",
},
}
if err := metricsExporter.Run(stopCh, lbs); err != nil {
return err
}
}
http.Handle("/alert", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
data := struct {
Value int `json:"value"`
}{}
defer Must(r.Body.Close())
if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusOK)
_, err := fmt.Fprint(w, "new value", data.Value)
Must(err)
alertMetrc.Set(float64(data.Value))
}))
if err := http.ListenAndServe(":8080", http.DefaultServeMux); err != nil {
close(stopCh)
glog.Fatal(err)
}
<-stopCh
return nil
},
}
rootCmd.PersistentFlags().AddGoFlagSet(flag.CommandLine)
Must(flag.CommandLine.Parse([]string{}))
metricsConf.AddFlags(rootCmd.PersistentFlags())
rootCmd.PersistentFlags().IntVar(¶llelProcess, "nums-of-parallel-req", 1, "nums of parallel request")
return rootCmd
}
func main() {
rootCmd := NewRootCmd()
if err := rootCmd.Execute(); err != nil {
glog.Fatal(err)
}
}
func Must(err error) {
if err != nil {
panic(err)
}
}