-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.go
224 lines (191 loc) · 4.45 KB
/
server.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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
package main
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
"github.com/gorilla/mux"
)
/*
Sample requests:
/put
{
"ts":"now",
"values" :[{
"value": 100
}]
}
/query
{
"begin":"-10m",
"end":"now"
}
*/
type (
// QueryRequest query
QueryRequest struct {
Columns string `json:"columns,omitempty"`
Begin string `json:"begin,omitempty"`
End string `json:"end,omitempty"`
IncludeInvalid bool `json:"include_invalid,omitempty"`
}
// QueryResponse for query
QueryResponse struct {
Begin int64 `json:"begin"`
End int64 `json:"end"`
Columns []string `json:"columns"`
Data [][]float32 `json:"data"`
}
// PutValue is one value to put with PutRequest
PutValue struct {
Column string `json:"column,omitempty"`
Value float32 `json:"value"`
}
// PutRequest - data for put request
PutRequest struct {
TS string `json:"ts,omitempty"`
Values []PutValue `json:"values"`
}
// Server handle rest request
Server struct {
Address string
router *mux.Router
DbFilename string
db *RRD
}
)
// Start server
func (s *Server) Start() {
s.router = mux.NewRouter()
s.router.HandleFunc("/query", s.queryHandler).Methods("POST")
s.router.HandleFunc("/put", s.putHandler).Methods("POST")
http.Handle("/", s.router)
f, err := OpenRRD(s.DbFilename, false)
if err != nil {
fmt.Println("Open db error: " + err.Error())
return
}
s.db = f
ticker := time.NewTicker(time.Second * 5)
go func() {
for _ = range ticker.C {
s.db.Flush()
}
}()
server := &http.Server{
Addr: s.Address,
}
fmt.Printf("Start listen on %s\n", s.Address)
server.ListenAndServe()
}
func (s *Server) queryHandler(w http.ResponseWriter, r *http.Request) {
Log("Server.queryHandler %s from %s", r.RequestURI, r.RemoteAddr)
var req QueryRequest
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
http.Error(w, fmt.Sprintf("decode error %s\n", err.Error()), http.StatusBadRequest)
return
}
LogDebug("Server.putHandler req: %+v", req)
if req.Begin == "" {
req.Begin = "0"
}
tsMin, ok := dateToTs(req.Begin)
if !ok {
http.Error(w, "bad begin date", http.StatusBadRequest)
return
}
if req.End == "" {
req.End = "now"
}
tsMax, ok := dateToTs(req.End)
if !ok {
http.Error(w, "bad end date", http.StatusBadRequest)
return
}
var columns []int
if len(req.Columns) > 0 {
cols, err := s.db.ParseColumnsNames(strings.Split(req.Columns, ","))
if err != nil {
http.Error(w, fmt.Sprintf("wrong columns: %s\n", err.Error()), http.StatusBadRequest)
return
}
columns = cols
}
resp := QueryResponse{
Begin: tsMin,
End: tsMax,
}
if rows, err := s.db.GetRange(tsMin, tsMax, columns, req.IncludeInvalid, true); err == nil {
for idx, row := range rows {
if idx == 0 {
for _, col := range row.Values {
resp.Columns = append(resp.Columns, s.db.ColumnName(col.Column))
}
}
var rrow []float32
for _, col := range row.Values {
if col.Valid {
rrow = append(rrow, col.Value)
} else {
rrow = append(rrow, 0)
}
}
resp.Data = append(resp.Data, rrow)
}
}
LogDebug("Server.queryHandler res: %+v", resp)
j, err := json.Marshal(resp)
if err != nil {
fmt.Printf("encode error %s\n", err.Error())
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(j)
}
func (s *Server) putHandler(w http.ResponseWriter, r *http.Request) {
Log("Server.putHandler %s from %s", r.RequestURI, r.RemoteAddr)
var req PutRequest
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
http.Error(w, fmt.Sprintf("decode error %s\n", err.Error()), http.StatusBadRequest)
return
}
LogDebug("Server.putHandler req: %+v", req)
if req.TS == "" {
req.TS = "0"
}
ts, ok := dateToTs(req.TS)
if !ok {
http.Error(w, "bad ts date", http.StatusBadRequest)
return
}
var values []Value
for idx, v := range req.Values {
value := Value{
TS: ts,
Value: v.Value,
Column: idx,
Valid: true,
}
if v.Column != "" {
c, err := s.db.ParseColumnName(v.Column)
if err != nil {
http.Error(w, "column in value "+string(idx), http.StatusBadRequest)
return
}
value.Column = c
}
values = append(values, value)
}
LogDebug("Server.putHandler res: %+v", values)
err = s.db.PutValues(values...)
if err != nil {
http.Error(w, "put error "+err.Error(), http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("ok"))
}