-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.go
180 lines (166 loc) · 5.62 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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
package main
import (
"flag"
"io/ioutil"
"net/http"
"os"
"path"
"time"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/golang/protobuf/proto"
"github.com/golang/snappy"
"github.com/kebe7jun/ropee/metrics"
"github.com/kebe7jun/ropee/storage"
"github.com/lestrrat/go-file-rotatelogs"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/prometheus/prompb"
)
type Config struct {
SplunkUrl string
SplunkMetricsIndex string
SplunkMetricsSourceType string
SplunkHECURL string
SplunkHECToken string
TimeoutSeconds int
ListenAddr string
LogFilePath string
Debug bool
}
var config Config
func loadRotateWriter(logPath, fileName string) *rotatelogs.RotateLogs {
writer, _ := rotatelogs.New(
path.Join(logPath, fileName)+".%Y%m%d%H%M",
rotatelogs.WithLinkName(path.Join(logPath, fileName)), // 生成软链,指向最新日志文件
rotatelogs.WithMaxAge(7*24*time.Hour), // 文件最大保存时间
rotatelogs.WithRotationTime(48*time.Hour), // 日志切割时间间隔
)
return writer
}
func loadLogger() log.Logger {
var logger log.Logger
if config.LogFilePath == "-" {
logger = log.NewLogfmtLogger(os.Stdout)
} else {
logger = log.NewLogfmtLogger(log.NewSyncWriter(loadRotateWriter(config.LogFilePath, "ropee.log")))
}
if config.Debug {
logger = level.NewFilter(logger, level.AllowDebug())
} else {
logger = level.NewFilter(logger, level.AllowInfo())
}
logger = log.With(logger, "time", log.DefaultTimestampUTC, "caller", log.DefaultCaller)
return logger
}
func initConfig() {
// init config
flag.StringVar(&config.SplunkUrl, "splunk-url", "https://127.0.0.1:8089", "Splunk Manage Url.")
flag.StringVar(&config.SplunkHECURL, "splunk-hec-url", "https://127.0.0.1:8088", "Splunk Http event collector url.")
flag.StringVar(&config.SplunkHECToken, "splunk-hec-token", "", "Splunk Http event collector token.")
flag.StringVar(&config.ListenAddr, "listen-addr", "127.0.0.1:9970", "Sopee listen addr.")
flag.StringVar(&config.SplunkMetricsIndex, "splunk-metrics-index", "*", "Index name.")
flag.StringVar(&config.SplunkMetricsSourceType, "splunk-metrics-sourcetype", "DaoCloud_promu_metrics", "The prometheus sourcetype name.")
flag.StringVar(&config.LogFilePath, "log-file-path", "/var/log", "Log files path.")
flag.IntVar(&config.TimeoutSeconds, "timeout", 60, "API timeout seconds.")
flag.BoolVar(&config.Debug, "debug", false, "Debug mode.")
flag.Parse()
}
func main() {
initConfig()
l := loadLogger()
http.Handle("/metrics", promhttp.Handler())
http.HandleFunc("/read", func(w http.ResponseWriter, r *http.Request) {
compressed, err := ioutil.ReadAll(r.Body)
if err != nil {
level.Error(l).Log("msg", "Read error", "err", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
reqBuf, err := snappy.Decode(nil, compressed)
if err != nil {
level.Error(l).Log("msg", "Decode error", "err", err.Error())
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
metrics.ReadRequestCounter.Add(1)
var req prompb.ReadRequest
if err := proto.Unmarshal(reqBuf, &req); err != nil {
level.Error(l).Log("msg", "Unmarshal error", "err", err.Error())
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
user, pass, _ := r.BasicAuth()
readClient, _ := storage.NewClient(
config.SplunkUrl,
user,
pass,
config.SplunkMetricsIndex,
config.SplunkMetricsSourceType,
config.SplunkHECURL, config.SplunkHECToken,
time.Second*time.Duration(config.TimeoutSeconds),
l,
)
resp, err := readClient.Read(&req)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
data, err := proto.Marshal(resp)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/x-protobuf")
w.Header().Set("Content-Encoding", "snappy")
compressed = snappy.Encode(nil, data)
if _, err := w.Write(compressed); err != nil {
level.Warn(l).Log("msg", "Error executing query", "query", req, "err", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
writeClient, _ := storage.NewClient(
config.SplunkUrl,
"",
"",
config.SplunkMetricsIndex,
config.SplunkMetricsSourceType,
config.SplunkHECURL, config.SplunkHECToken,
time.Second*time.Duration(config.TimeoutSeconds),
l,
)
http.HandleFunc("/write", func(w http.ResponseWriter, r *http.Request) {
compressed, err := ioutil.ReadAll(r.Body)
if err != nil {
level.Error(l).Log("msg", "Read error", "err", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
reqBuf, err := snappy.Decode(nil, compressed)
if err != nil {
level.Error(l).Log("msg", "Decode error", "err", err.Error())
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
metrics.WriteRequestCounter.Add(1)
var req prompb.WriteRequest
if err := proto.Unmarshal(reqBuf, &req); err != nil {
level.Error(l).Log("msg", "Unmarshal error", "err", err.Error())
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
err = writeClient.Write(&req)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(200)
if _, err := w.Write([]byte("ok")); err != nil {
level.Error(l).Log("action", "write", "err", err)
}
})
level.Info(l).Log("msg", "starting server...", "listen", config.ListenAddr)
if err := http.ListenAndServe(config.ListenAddr, nil); err != nil {
level.Error(l).Log("action", "serve", "err", err)
}
}