chronograf/server/influx.go

187 lines
4.7 KiB
Go
Raw Normal View History

2017-02-17 20:02:02 +00:00
package server
import (
"bytes"
"crypto/tls"
"encoding/csv"
2017-02-17 20:02:02 +00:00
"encoding/json"
"fmt"
"net"
2017-02-17 20:02:02 +00:00
"net/http"
"net/http/httputil"
"net/url"
"strings"
"time"
2017-02-17 20:02:02 +00:00
"github.com/influxdata/chronograf"
uuid "github.com/influxdata/chronograf/id"
"github.com/influxdata/chronograf/influx"
2017-02-17 20:02:02 +00:00
)
// 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
2017-02-17 20:02:02 +00:00
}
// Influx proxies requests to influxdb.
func (s *Service) Influx(w http.ResponseWriter, r *http.Request) {
2017-02-17 20:02:02 +00:00
id, err := paramID("id", r)
if err != nil {
Error(w, http.StatusUnprocessableEntity, err.Error(), s.Logger)
2017-02-17 20:02:02 +00:00
return
}
var req chronograf.Query
if err = json.NewDecoder(r.Body).Decode(&req); err != nil {
invalidJSON(w, s.Logger)
2017-02-17 20:02:02 +00:00
return
}
if err = ValidInfluxRequest(req); err != nil {
invalidData(w, err, s.Logger)
2017-02-17 20:02:02 +00:00
return
}
ctx := r.Context()
src, err := s.Store.Sources(ctx).Get(ctx, id)
2017-02-17 20:02:02 +00:00
if err != nil {
notFound(w, id, s.Logger)
2017-02-17 20:02:02 +00:00
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)
2017-02-17 20:02:02 +00:00
return
}
// inspect request command to specify additional request parameters
setupQueryFromCommand(&req)
response, err := ts.Query(ctx, req)
2017-02-17 20:02:02 +00:00
if err != nil {
if err == chronograf.ErrUpstreamTimeout {
msg := "Timeout waiting for Influx response"
Error(w, http.StatusRequestTimeout, msg, s.Logger)
2017-02-17 20:02:02 +00:00
return
}
// TODO: Here I want to return the error code from influx.
Error(w, http.StatusBadRequest, err.Error(), s.Logger)
2017-02-17 20:02:02 +00:00
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
}
2017-02-17 20:02:02 +00:00
res := postInfluxResponse{
Results: response,
UUID: uniqueID,
2017-02-17 20:02:02 +00:00
}
encodeJSON(w, http.StatusOK, res, s.Logger)
2017-02-17 20:02:02 +00:00
}
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
}
u.Path = "/write"
u.RawQuery = r.URL.RawQuery
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:])
}
}
}
}