This repository has been archived by the owner on Jul 19, 2022. It is now read-only.
forked from influxdata/influxdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
196 lines (169 loc) · 4.64 KB
/
handler.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
package opentsdb
import (
"bufio"
"compress/gzip"
"encoding/json"
"errors"
"io"
"log"
"net"
"net/http"
"sync"
"sync/atomic"
"time"
"github.com/influxdata/influxdb"
"github.com/influxdata/influxdb/models"
)
// Handler is an http.Handler for the service.
type Handler struct {
Database string
RetentionPolicy string
PointsWriter interface {
WritePoints(database, retentionPolicy string, consistencyLevel models.ConsistencyLevel, points []models.Point) error
}
Logger *log.Logger
stats *Statistics
}
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/metadata/put":
w.WriteHeader(http.StatusNoContent)
case "/api/put":
h.servePut(w, r)
default:
http.NotFound(w, r)
}
}
// ServeHTTP implements OpenTSDB's HTTP /api/put endpoint
func (h *Handler) servePut(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
// Require POST method.
if r.Method != "POST" {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
// Wrap reader if it's gzip encoded.
var br *bufio.Reader
if r.Header.Get("Content-Encoding") == "gzip" {
zr, err := gzip.NewReader(r.Body)
if err != nil {
http.Error(w, "could not read gzip, "+err.Error(), http.StatusBadRequest)
return
}
br = bufio.NewReader(zr)
} else {
br = bufio.NewReader(r.Body)
}
// Lookahead at the first byte.
f, err := br.Peek(1)
if err != nil || len(f) != 1 {
http.Error(w, "peek error: "+err.Error(), http.StatusBadRequest)
return
}
// Peek to see if this is a JSON array.
var multi bool
switch f[0] {
case '{':
case '[':
multi = true
default:
http.Error(w, "expected JSON array or hash", http.StatusBadRequest)
return
}
// Decode JSON data into slice of points.
dps := make([]point, 1)
if dec := json.NewDecoder(br); multi {
if err = dec.Decode(&dps); err != nil {
http.Error(w, "json array decode error", http.StatusBadRequest)
return
}
} else {
if err = dec.Decode(&dps[0]); err != nil {
http.Error(w, "json object decode error", http.StatusBadRequest)
return
}
}
// Convert points into TSDB points.
points := make([]models.Point, 0, len(dps))
for i := range dps {
p := dps[i]
// Convert timestamp to Go time.
// If time value is over a billion then it's microseconds.
var ts time.Time
if p.Time < 10000000000 {
ts = time.Unix(p.Time, 0)
} else {
ts = time.Unix(p.Time/1000, (p.Time%1000)*1000)
}
pt, err := models.NewPoint(p.Metric, models.NewTags(p.Tags), map[string]interface{}{"value": p.Value}, ts)
if err != nil {
h.Logger.Printf("Dropping point %v: %v", p.Metric, err)
if h.stats != nil {
atomic.AddInt64(&h.stats.InvalidDroppedPoints, 1)
}
continue
}
points = append(points, pt)
}
// Write points.
if err := h.PointsWriter.WritePoints(h.Database, h.RetentionPolicy, models.ConsistencyLevelAny, points); influxdb.IsClientError(err) {
h.Logger.Println("write series error: ", err)
http.Error(w, "write series error: "+err.Error(), http.StatusBadRequest)
return
} else if err != nil {
h.Logger.Println("write series error: ", err)
http.Error(w, "write series error: "+err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusNoContent)
}
// chanListener represents a listener that receives connections through a channel.
type chanListener struct {
addr net.Addr
ch chan net.Conn
done chan struct{}
closer sync.Once // closer ensures that Close is idempotent.
}
// newChanListener returns a new instance of chanListener.
func newChanListener(addr net.Addr) *chanListener {
return &chanListener{
addr: addr,
ch: make(chan net.Conn),
done: make(chan struct{}),
}
}
func (ln *chanListener) Accept() (net.Conn, error) {
errClosed := errors.New("network connection closed")
select {
case <-ln.done:
return nil, errClosed
case conn, ok := <-ln.ch:
if !ok {
return nil, errClosed
}
return conn, nil
}
}
// Close closes the connection channel.
func (ln *chanListener) Close() error {
ln.closer.Do(func() {
close(ln.done)
})
return nil
}
// Addr returns the network address of the listener.
func (ln *chanListener) Addr() net.Addr { return ln.addr }
// readerConn represents a net.Conn with an assignable reader.
type readerConn struct {
net.Conn
r io.Reader
}
// Read implements the io.Reader interface.
func (conn *readerConn) Read(b []byte) (n int, err error) { return conn.r.Read(b) }
// point represents an incoming JSON data point.
type point struct {
Metric string `json:"metric"`
Time int64 `json:"timestamp"`
Value float64 `json:"value"`
Tags map[string]string `json:"tags,omitempty"`
}