2018-03-28 00:30:51 +00:00
|
|
|
package influxdb
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"crypto/tls"
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
2018-03-28 01:36:08 +00:00
|
|
|
"net"
|
2018-03-28 00:30:51 +00:00
|
|
|
"net/http"
|
|
|
|
"net/url"
|
|
|
|
"path"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/influxdata/telegraf"
|
2018-10-05 22:06:41 +00:00
|
|
|
"github.com/influxdata/telegraf/internal"
|
2018-03-28 00:30:51 +00:00
|
|
|
"github.com/influxdata/telegraf/plugins/serializers/influx"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2018-10-11 19:25:21 +00:00
|
|
|
defaultRequestTimeout = time.Second * 5
|
|
|
|
defaultDatabase = "telegraf"
|
2018-03-28 00:30:51 +00:00
|
|
|
errStringDatabaseNotFound = "database not found"
|
|
|
|
errStringHintedHandoffNotEmpty = "hinted handoff queue not empty"
|
|
|
|
errStringPartialWrite = "partial write"
|
|
|
|
errStringPointsBeyondRP = "points beyond retention policy"
|
|
|
|
errStringUnableToParse = "unable to parse"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
// Escape an identifier in InfluxQL.
|
|
|
|
escapeIdentifier = strings.NewReplacer(
|
|
|
|
"\n", `\n`,
|
|
|
|
`\`, `\\`,
|
|
|
|
`"`, `\"`,
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
2019-02-27 18:54:02 +00:00
|
|
|
// APIError is a general error reported by the InfluxDB server
|
2018-03-28 00:30:51 +00:00
|
|
|
type APIError struct {
|
|
|
|
StatusCode int
|
|
|
|
Title string
|
|
|
|
Description string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e APIError) Error() string {
|
|
|
|
if e.Description != "" {
|
|
|
|
return fmt.Sprintf("%s: %s", e.Title, e.Description)
|
|
|
|
}
|
|
|
|
return e.Title
|
|
|
|
}
|
|
|
|
|
2019-02-27 18:54:02 +00:00
|
|
|
type DatabaseNotFoundError struct {
|
|
|
|
APIError
|
|
|
|
Database string
|
|
|
|
}
|
|
|
|
|
2018-03-28 00:30:51 +00:00
|
|
|
// QueryResponse is the response body from the /query endpoint
|
|
|
|
type QueryResponse struct {
|
|
|
|
Results []QueryResult `json:"results"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type QueryResult struct {
|
|
|
|
Err string `json:"error,omitempty"`
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r QueryResponse) Error() string {
|
|
|
|
if len(r.Results) > 0 {
|
|
|
|
return r.Results[0].Err
|
|
|
|
}
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
|
|
|
// WriteResponse is the response body from the /write endpoint
|
|
|
|
type WriteResponse struct {
|
|
|
|
Err string `json:"error,omitempty"`
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r WriteResponse) Error() string {
|
|
|
|
return r.Err
|
|
|
|
}
|
|
|
|
|
|
|
|
type HTTPConfig struct {
|
2019-02-27 18:54:02 +00:00
|
|
|
URL *url.URL
|
|
|
|
UserAgent string
|
|
|
|
Timeout time.Duration
|
|
|
|
Username string
|
|
|
|
Password string
|
|
|
|
TLSConfig *tls.Config
|
|
|
|
Proxy *url.URL
|
|
|
|
Headers map[string]string
|
|
|
|
ContentEncoding string
|
|
|
|
Database string
|
|
|
|
DatabaseTag string
|
2019-07-30 21:16:51 +00:00
|
|
|
ExcludeDatabaseTag bool
|
2019-02-27 18:54:02 +00:00
|
|
|
RetentionPolicy string
|
|
|
|
Consistency string
|
|
|
|
SkipDatabaseCreation bool
|
2018-03-28 00:30:51 +00:00
|
|
|
|
2018-03-29 20:31:43 +00:00
|
|
|
InfluxUintSupport bool `toml:"influx_uint_support"`
|
|
|
|
Serializer *influx.Serializer
|
2019-08-21 23:49:07 +00:00
|
|
|
log telegraf.Logger
|
2018-03-28 00:30:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type httpClient struct {
|
2019-02-27 18:54:02 +00:00
|
|
|
client *http.Client
|
|
|
|
config HTTPConfig
|
|
|
|
createdDatabases map[string]bool
|
2019-08-21 23:49:07 +00:00
|
|
|
|
|
|
|
log telegraf.Logger
|
2018-03-28 00:30:51 +00:00
|
|
|
}
|
|
|
|
|
2019-02-27 18:54:02 +00:00
|
|
|
func NewHTTPClient(config HTTPConfig) (*httpClient, error) {
|
2018-03-28 00:30:51 +00:00
|
|
|
if config.URL == nil {
|
|
|
|
return nil, ErrMissingURL
|
|
|
|
}
|
|
|
|
|
2019-02-27 18:54:02 +00:00
|
|
|
if config.Database == "" {
|
|
|
|
config.Database = defaultDatabase
|
2018-03-28 00:30:51 +00:00
|
|
|
}
|
|
|
|
|
2019-02-27 18:54:02 +00:00
|
|
|
if config.Timeout == 0 {
|
|
|
|
config.Timeout = defaultRequestTimeout
|
2018-03-28 00:30:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
userAgent := config.UserAgent
|
|
|
|
if userAgent == "" {
|
2018-10-11 19:25:21 +00:00
|
|
|
userAgent = "Telegraf/" + internal.Version()
|
2018-03-28 00:30:51 +00:00
|
|
|
}
|
|
|
|
|
2019-02-27 18:54:02 +00:00
|
|
|
if config.Headers == nil {
|
|
|
|
config.Headers = make(map[string]string)
|
|
|
|
}
|
|
|
|
config.Headers["User-Agent"] = userAgent
|
2018-03-28 00:30:51 +00:00
|
|
|
for k, v := range config.Headers {
|
2019-02-27 18:54:02 +00:00
|
|
|
config.Headers[k] = v
|
2018-03-28 00:30:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var proxy func(*http.Request) (*url.URL, error)
|
|
|
|
if config.Proxy != nil {
|
|
|
|
proxy = http.ProxyURL(config.Proxy)
|
|
|
|
} else {
|
|
|
|
proxy = http.ProxyFromEnvironment
|
|
|
|
}
|
|
|
|
|
2019-02-27 18:54:02 +00:00
|
|
|
if config.Serializer == nil {
|
|
|
|
config.Serializer = influx.NewSerializer()
|
2018-04-05 18:08:31 +00:00
|
|
|
}
|
2018-03-28 00:30:51 +00:00
|
|
|
|
2018-03-28 01:36:08 +00:00
|
|
|
var transport *http.Transport
|
|
|
|
switch config.URL.Scheme {
|
|
|
|
case "http", "https":
|
|
|
|
transport = &http.Transport{
|
|
|
|
Proxy: proxy,
|
|
|
|
TLSClientConfig: config.TLSConfig,
|
|
|
|
}
|
|
|
|
case "unix":
|
|
|
|
transport = &http.Transport{
|
|
|
|
Dial: func(_, _ string) (net.Conn, error) {
|
|
|
|
return net.DialTimeout(
|
|
|
|
config.URL.Scheme,
|
|
|
|
config.URL.Path,
|
|
|
|
defaultRequestTimeout,
|
|
|
|
)
|
|
|
|
},
|
|
|
|
}
|
|
|
|
default:
|
|
|
|
return nil, fmt.Errorf("unsupported scheme %q", config.URL.Scheme)
|
|
|
|
}
|
|
|
|
|
2018-03-28 00:30:51 +00:00
|
|
|
client := &httpClient{
|
|
|
|
client: &http.Client{
|
2019-02-27 18:54:02 +00:00
|
|
|
Timeout: config.Timeout,
|
2018-03-28 01:36:08 +00:00
|
|
|
Transport: transport,
|
2018-03-28 00:30:51 +00:00
|
|
|
},
|
2019-02-27 18:54:02 +00:00
|
|
|
createdDatabases: make(map[string]bool),
|
|
|
|
config: config,
|
2019-08-21 23:49:07 +00:00
|
|
|
log: config.log,
|
2018-03-28 00:30:51 +00:00
|
|
|
}
|
|
|
|
return client, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// URL returns the origin URL that this client connects too.
|
|
|
|
func (c *httpClient) URL() string {
|
2019-02-27 18:54:02 +00:00
|
|
|
return c.config.URL.String()
|
2018-03-28 00:30:51 +00:00
|
|
|
}
|
|
|
|
|
2019-08-21 23:49:07 +00:00
|
|
|
func (c *httpClient) SetLogger(log telegraf.Logger) {
|
|
|
|
c.log = log
|
|
|
|
}
|
|
|
|
|
2019-02-27 18:54:02 +00:00
|
|
|
// Database returns the default database that this client connects too.
|
2018-03-28 00:30:51 +00:00
|
|
|
func (c *httpClient) Database() string {
|
2019-02-27 18:54:02 +00:00
|
|
|
return c.config.Database
|
2018-03-28 00:30:51 +00:00
|
|
|
}
|
|
|
|
|
2018-10-19 18:12:01 +00:00
|
|
|
// CreateDatabase attempts to create a new database in the InfluxDB server.
|
2018-03-28 00:30:51 +00:00
|
|
|
// Note that some names are not allowed by the server, notably those with
|
|
|
|
// non-printable characters or slashes.
|
2019-02-27 18:54:02 +00:00
|
|
|
func (c *httpClient) CreateDatabase(ctx context.Context, database string) error {
|
2018-03-28 00:30:51 +00:00
|
|
|
query := fmt.Sprintf(`CREATE DATABASE "%s"`,
|
2019-02-27 18:54:02 +00:00
|
|
|
escapeIdentifier.Replace(database))
|
2018-03-28 00:30:51 +00:00
|
|
|
|
|
|
|
req, err := c.makeQueryRequest(query)
|
|
|
|
|
|
|
|
resp, err := c.client.Do(req.WithContext(ctx))
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
|
|
queryResp := &QueryResponse{}
|
|
|
|
dec := json.NewDecoder(resp.Body)
|
|
|
|
err = dec.Decode(queryResp)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
if resp.StatusCode == 200 {
|
2019-02-27 18:54:02 +00:00
|
|
|
c.createdDatabases[database] = true
|
2018-03-28 00:30:51 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return &APIError{
|
|
|
|
StatusCode: resp.StatusCode,
|
|
|
|
Title: resp.Status,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Even with a 200 response there can be an error
|
|
|
|
if resp.StatusCode == http.StatusOK && queryResp.Error() == "" {
|
2019-02-27 18:54:02 +00:00
|
|
|
c.createdDatabases[database] = true
|
2018-03-28 00:30:51 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return &APIError{
|
|
|
|
StatusCode: resp.StatusCode,
|
|
|
|
Title: resp.Status,
|
|
|
|
Description: queryResp.Error(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Write sends the metrics to InfluxDB
|
|
|
|
func (c *httpClient) Write(ctx context.Context, metrics []telegraf.Metric) error {
|
2019-02-27 18:54:02 +00:00
|
|
|
batches := make(map[string][]telegraf.Metric)
|
|
|
|
if c.config.DatabaseTag == "" {
|
|
|
|
err := c.writeBatch(ctx, c.config.Database, metrics)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
for _, metric := range metrics {
|
|
|
|
db, ok := metric.GetTag(c.config.DatabaseTag)
|
|
|
|
if !ok {
|
|
|
|
db = c.config.Database
|
|
|
|
}
|
|
|
|
|
|
|
|
if _, ok := batches[db]; !ok {
|
|
|
|
batches[db] = make([]telegraf.Metric, 0)
|
|
|
|
}
|
|
|
|
|
2019-07-30 21:16:51 +00:00
|
|
|
if c.config.ExcludeDatabaseTag {
|
|
|
|
metric.RemoveTag(c.config.DatabaseTag)
|
|
|
|
}
|
|
|
|
|
2019-02-27 18:54:02 +00:00
|
|
|
batches[db] = append(batches[db], metric)
|
|
|
|
}
|
|
|
|
|
|
|
|
for db, batch := range batches {
|
|
|
|
if !c.config.SkipDatabaseCreation && !c.createdDatabases[db] {
|
|
|
|
err := c.CreateDatabase(ctx, db)
|
|
|
|
if err != nil {
|
2019-08-21 23:49:07 +00:00
|
|
|
c.log.Warnf("when writing to [%s]: database %q creation failed: %v",
|
2019-02-27 18:54:02 +00:00
|
|
|
c.config.URL, db, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
err := c.writeBatch(ctx, db, batch)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *httpClient) writeBatch(ctx context.Context, db string, metrics []telegraf.Metric) error {
|
|
|
|
url, err := makeWriteURL(c.config.URL, db, c.config.RetentionPolicy, c.config.Consistency)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2018-03-28 00:30:51 +00:00
|
|
|
|
2019-02-27 18:54:02 +00:00
|
|
|
reader := influx.NewReader(metrics, c.config.Serializer)
|
|
|
|
req, err := c.makeWriteRequest(url, reader)
|
2018-03-28 00:30:51 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
resp, err := c.client.Do(req.WithContext(ctx))
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
|
|
if resp.StatusCode == http.StatusNoContent {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
writeResp := &WriteResponse{}
|
|
|
|
dec := json.NewDecoder(resp.Body)
|
|
|
|
|
|
|
|
var desc string
|
|
|
|
err = dec.Decode(writeResp)
|
|
|
|
if err == nil {
|
|
|
|
desc = writeResp.Err
|
|
|
|
}
|
|
|
|
|
|
|
|
if strings.Contains(desc, errStringDatabaseNotFound) {
|
2019-02-27 18:54:02 +00:00
|
|
|
return &DatabaseNotFoundError{
|
|
|
|
APIError: APIError{
|
|
|
|
StatusCode: resp.StatusCode,
|
|
|
|
Title: resp.Status,
|
|
|
|
Description: desc,
|
|
|
|
},
|
|
|
|
Database: db,
|
2018-03-28 00:30:51 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// This "error" is an informational message about the state of the
|
|
|
|
// InfluxDB cluster.
|
|
|
|
if strings.Contains(desc, errStringHintedHandoffNotEmpty) {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Points beyond retention policy is returned when points are immediately
|
|
|
|
// discarded for being older than the retention policy. Usually this not
|
|
|
|
// a cause for concern and we don't want to retry.
|
|
|
|
if strings.Contains(desc, errStringPointsBeyondRP) {
|
2019-08-21 23:49:07 +00:00
|
|
|
c.log.Warnf("when writing to [%s]: received error %v",
|
2018-03-28 00:30:51 +00:00
|
|
|
c.URL(), desc)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Other partial write errors, such as "field type conflict", are not
|
|
|
|
// correctable at this point and so the point is dropped instead of
|
|
|
|
// retrying.
|
|
|
|
if strings.Contains(desc, errStringPartialWrite) {
|
2019-08-21 23:49:07 +00:00
|
|
|
c.log.Errorf("when writing to [%s]: received error %v; discarding points",
|
2018-03-28 00:30:51 +00:00
|
|
|
c.URL(), desc)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// This error indicates a bug in either Telegraf line protocol
|
|
|
|
// serialization, retries would not be successful.
|
|
|
|
if strings.Contains(desc, errStringUnableToParse) {
|
2019-08-21 23:49:07 +00:00
|
|
|
c.log.Errorf("when writing to [%s]: received error %v; discarding points",
|
2018-03-28 00:30:51 +00:00
|
|
|
c.URL(), desc)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return &APIError{
|
|
|
|
StatusCode: resp.StatusCode,
|
|
|
|
Title: resp.Status,
|
|
|
|
Description: desc,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *httpClient) makeQueryRequest(query string) (*http.Request, error) {
|
2019-02-27 18:54:02 +00:00
|
|
|
queryURL, err := makeQueryURL(c.config.URL)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2018-03-28 00:30:51 +00:00
|
|
|
params := url.Values{}
|
|
|
|
params.Set("q", query)
|
|
|
|
form := strings.NewReader(params.Encode())
|
|
|
|
|
2019-02-27 18:54:02 +00:00
|
|
|
req, err := http.NewRequest("POST", queryURL, form)
|
2018-03-28 00:30:51 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
|
|
|
c.addHeaders(req)
|
|
|
|
|
|
|
|
return req, nil
|
|
|
|
}
|
|
|
|
|
2019-02-27 18:54:02 +00:00
|
|
|
func (c *httpClient) makeWriteRequest(url string, body io.Reader) (*http.Request, error) {
|
2018-03-28 00:30:51 +00:00
|
|
|
var err error
|
2019-02-27 18:54:02 +00:00
|
|
|
if c.config.ContentEncoding == "gzip" {
|
2018-10-05 22:06:41 +00:00
|
|
|
body, err = internal.CompressWithGzip(body)
|
2018-03-28 00:30:51 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-02-27 18:54:02 +00:00
|
|
|
req, err := http.NewRequest("POST", url, body)
|
2018-03-28 00:30:51 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
req.Header.Set("Content-Type", "text/plain; charset=utf-8")
|
|
|
|
c.addHeaders(req)
|
|
|
|
|
2019-02-27 18:54:02 +00:00
|
|
|
if c.config.ContentEncoding == "gzip" {
|
2018-03-28 00:30:51 +00:00
|
|
|
req.Header.Set("Content-Encoding", "gzip")
|
|
|
|
}
|
|
|
|
|
|
|
|
return req, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *httpClient) addHeaders(req *http.Request) {
|
2019-02-27 18:54:02 +00:00
|
|
|
if c.config.Username != "" || c.config.Password != "" {
|
|
|
|
req.SetBasicAuth(c.config.Username, c.config.Password)
|
2018-03-28 00:30:51 +00:00
|
|
|
}
|
|
|
|
|
2019-02-27 18:54:02 +00:00
|
|
|
for header, value := range c.config.Headers {
|
2018-03-28 00:30:51 +00:00
|
|
|
req.Header.Set(header, value)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-04-05 18:08:31 +00:00
|
|
|
func makeWriteURL(loc *url.URL, db, rp, consistency string) (string, error) {
|
2018-03-28 00:30:51 +00:00
|
|
|
params := url.Values{}
|
|
|
|
params.Set("db", db)
|
|
|
|
|
|
|
|
if rp != "" {
|
|
|
|
params.Set("rp", rp)
|
|
|
|
}
|
|
|
|
|
|
|
|
if consistency != "one" && consistency != "" {
|
|
|
|
params.Set("consistency", consistency)
|
|
|
|
}
|
|
|
|
|
|
|
|
u := *loc
|
2018-03-28 01:36:08 +00:00
|
|
|
switch u.Scheme {
|
|
|
|
case "unix":
|
|
|
|
u.Scheme = "http"
|
|
|
|
u.Host = "127.0.0.1"
|
|
|
|
u.Path = "/write"
|
2018-04-05 18:08:31 +00:00
|
|
|
case "http", "https":
|
2018-03-28 01:36:08 +00:00
|
|
|
u.Path = path.Join(u.Path, "write")
|
2018-04-05 18:08:31 +00:00
|
|
|
default:
|
|
|
|
return "", fmt.Errorf("unsupported scheme: %q", loc.Scheme)
|
2018-03-28 01:36:08 +00:00
|
|
|
}
|
2018-03-28 00:30:51 +00:00
|
|
|
u.RawQuery = params.Encode()
|
2018-04-05 18:08:31 +00:00
|
|
|
return u.String(), nil
|
2018-03-28 00:30:51 +00:00
|
|
|
}
|
|
|
|
|
2018-04-05 18:08:31 +00:00
|
|
|
func makeQueryURL(loc *url.URL) (string, error) {
|
2018-03-28 00:30:51 +00:00
|
|
|
u := *loc
|
2018-03-28 01:36:08 +00:00
|
|
|
switch u.Scheme {
|
|
|
|
case "unix":
|
|
|
|
u.Scheme = "http"
|
|
|
|
u.Host = "127.0.0.1"
|
|
|
|
u.Path = "/query"
|
2018-04-05 18:08:31 +00:00
|
|
|
case "http", "https":
|
2018-03-28 01:36:08 +00:00
|
|
|
u.Path = path.Join(u.Path, "query")
|
2018-04-05 18:08:31 +00:00
|
|
|
default:
|
|
|
|
return "", fmt.Errorf("unsupported scheme: %q", loc.Scheme)
|
2018-03-28 01:36:08 +00:00
|
|
|
}
|
2018-04-05 18:08:31 +00:00
|
|
|
return u.String(), nil
|
2018-03-28 00:30:51 +00:00
|
|
|
}
|
2019-05-31 23:55:31 +00:00
|
|
|
|
|
|
|
func (c *httpClient) Close() {
|
|
|
|
internal.CloseIdleConnections(c.client)
|
|
|
|
}
|