forked from influxdata/chronograf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinflux.go
198 lines (178 loc) · 5.08 KB
/
influx.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
package server
import (
"bytes"
"crypto/tls"
"encoding/csv"
"encoding/json"
"fmt"
"net"
"net/http"
"net/http/httputil"
"net/url"
"strings"
"time"
"github.com/influxdata/chronograf"
uuid "github.com/influxdata/chronograf/id"
"github.com/influxdata/chronograf/influx"
"github.com/influxdata/chronograf/util"
)
// ValidInfluxRequest checks if queries specify a command.
func ValidInfluxRequest(p chronograf.Query) error {
if p.Command == "" {
return fmt.Errorf("query field required")
}
return nil
}
type postInfluxResponse struct {
Results interface{} `json:"results"` // results from influx
UUID string `json:"uuid,omitempty"` // uuid passed from client to identify results
}
// Influx proxies requests to influxdb.
func (s *Service) Influx(w http.ResponseWriter, r *http.Request) {
id, err := paramID("id", r)
if err != nil {
Error(w, http.StatusUnprocessableEntity, err.Error(), s.Logger)
return
}
var req chronograf.Query
if err = json.NewDecoder(r.Body).Decode(&req); err != nil {
invalidJSON(w, s.Logger)
return
}
if err = ValidInfluxRequest(req); err != nil {
invalidData(w, err, s.Logger)
return
}
ctx := r.Context()
src, err := s.Store.Sources(ctx).Get(ctx, id)
if err != nil {
notFound(w, id, s.Logger)
return
}
ts, err := s.TimeSeries(src)
if err != nil {
msg := fmt.Sprintf("Unable to connect to source %d: %v", id, err)
Error(w, http.StatusBadRequest, msg, s.Logger)
return
}
if err = ts.Connect(ctx, &src); err != nil {
msg := fmt.Sprintf("Unable to connect to source %d: %v", id, err)
Error(w, http.StatusBadRequest, msg, s.Logger)
return
}
// inspect request command to specify additional request parameters
setupQueryFromCommand(&req)
response, err := ts.Query(ctx, req)
if err != nil {
if err == chronograf.ErrUpstreamTimeout {
msg := "Timeout waiting for Influx response"
Error(w, http.StatusRequestTimeout, msg, s.Logger)
return
}
// TODO: Here I want to return the error code from influx.
Error(w, http.StatusBadRequest, err.Error(), s.Logger)
return
}
uniqueID := req.UUID
if uniqueID == "" {
newUUID, err := (&uuid.UUID{}).Generate()
if err != nil {
Error(w, http.StatusInternalServerError, "Failed to create a unique identifier", s.Logger)
return
}
uniqueID = newUUID
}
res := postInfluxResponse{
Results: response,
UUID: uniqueID,
}
encodeJSON(w, http.StatusOK, res, s.Logger)
}
func (s *Service) Write(w http.ResponseWriter, r *http.Request) {
id, err := paramID("id", r)
if err != nil {
Error(w, http.StatusUnprocessableEntity, err.Error(), s.Logger)
return
}
ctx := r.Context()
src, err := s.Store.Sources(ctx).Get(ctx, id)
if err != nil {
notFound(w, id, s.Logger)
return
}
u, err := url.Parse(src.URL)
if err != nil {
msg := fmt.Sprintf("Error parsing source url: %v", err)
Error(w, http.StatusUnprocessableEntity, msg, s.Logger)
return
}
query := r.URL.Query()
version := query.Get("v")
query.Del("v")
if strings.HasPrefix(version, "2") {
u = util.AppendPath(u, "/api/v2/write")
// v2 organization name is stored in username (org does not matter against v1)
query.Set("org", src.Username)
query.Set("bucket", query.Get("db"))
query.Del("db")
} else {
u = util.AppendPath(u, "/write")
}
u.RawQuery = query.Encode()
director := func(req *http.Request) {
// Set the Host header of the original source URL
req.Host = u.Host
req.URL = u
// Because we are acting as a proxy, influxdb needs to have the
// basic auth or bearer token information set as a header directly
auth := influx.DefaultAuthorization(&src)
auth.Set(req)
}
proxy := &httputil.ReverseProxy{
Director: director,
}
// The connection to influxdb is using a self-signed certificate.
// This modifies uses the same values as http.DefaultTransport but specifies
// InsecureSkipVerify
if src.InsecureSkipVerify {
proxy.Transport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
}
proxy.ServeHTTP(w, r)
}
// setupQueryFromCommand set query parameters from its command
func setupQueryFromCommand(req *chronograf.Query) {
// allow to set active database with USE command, examples:
// use mydb
// use "mydb"
// USE "mydb"."myrp"
// use "mydb.myrp"
// use mydb.myrp
if strings.HasPrefix(req.Command, "use ") || strings.HasPrefix(req.Command, "USE ") {
if nextCommand := strings.IndexRune(req.Command, ';'); nextCommand > 4 {
dbSpec := strings.TrimSpace(req.Command[4:nextCommand])
dbSpecReader := csv.NewReader(bytes.NewReader(([]byte)(dbSpec)))
dbSpecReader.Comma = '.'
if dbrp, err := dbSpecReader.Read(); err == nil {
if len(dbrp) > 0 {
req.DB = dbrp[0]
}
if len(dbrp) > 1 {
req.RP = dbrp[1]
}
req.Command = strings.TrimSpace(req.Command[nextCommand+1:])
}
}
}
}