influxdb-client-go: github.com/influxdata/influxdb-client-go Index | Examples | Files | Directories

package influxdb

import "github.com/influxdata/influxdb-client-go"

Index

Examples

Package Files

client.go clientoptions.go errors.go http.go models.go query.go setup.go useragent.go write.go

Constants

const (
    EInternal            = "internal error"
    ENotFound            = "not found"
    EConflict            = "conflict"             // action cannot be performed
    EInvalid             = "invalid"              // validation failed
    EUnprocessableEntity = "unprocessable entity" // data type is correct, but out of range
    EEmptyValue          = "empty value"
    EUnavailable         = "unavailable"
    EForbidden           = "forbidden"
    ETooManyRequests     = "too many requests"
    EUnauthorized        = "unauthorized"
    EMethodNotAllowed    = "method not allowed"
)

Error code constants copied from influxdb

Variables

var ErrUnimplemented = errors.New("unimplemented")

ErrUnimplemented is an error for when pieces of the client's functionality is unimplemented.

func HTTPClientWithTLSConfig Uses

func HTTPClientWithTLSConfig(conf *tls.Config) *http.Client

HTTPClientWithTLSConfig returns an *http.Client with sane timeouts and the provided TLSClientConfig.

type Client Uses

type Client struct {
    // contains filtered or unexported fields
}

Client is a client for writing to influx.

func New Uses

func New(connection string, token string, options ...Option) (*Client, error)

New creates a new Client. The client is concurrency safe, so feel free to use it and abuse it to your heart's content.

func (*Client) Close Uses

func (c *Client) Close() error

Close closes any idle connections on the Client.

func (*Client) Ping Uses

func (c *Client) Ping(ctx context.Context) error

Ping checks the status of cluster.

func (*Client) QueryCSV Uses

func (c *Client) QueryCSV(ctx context.Context, flux string, org string, extern ...interface{}) (*QueryCSVResult, error)

QueryCSV returns the result of a flux query. TODO: annotations

func (*Client) Setup Uses

func (c *Client) Setup(ctx context.Context, bucket, org string, retentionPeriodHrs int) (*SetupResult, error)

Setup sets up a new influxdb server. It requires a client be set up with a username and password. If successful will add a token to the client. RetentionPeriodHrs of zero will result in infinite retention.

Code:

// just us setting up the server so the example will work.  You will likely have to use the old fasioned way to get an *http.Client and address
// alternatively you can leave the *http.Client nil, and it will intelligently create one with sane defaults.
myHTTPClient, myHTTPInfluxAddress, teardown := setupMockServer()
defer teardown() // we shut down our server at the end of the test, obviously you won't be doing this.

influx, err := influxdb.New(myHTTPInfluxAddress, "", influxdb.WithUserAndPass("my-username", "my-password"), influxdb.WithHTTPClient(myHTTPClient))
if err != nil {
    panic(err) // error handling here, normally we wouldn't use fmt, but it works for the example
}
resp, err := influx.Setup(context.Background(), "my-bucket", "my-org", 32)
if err != nil {
    log.Fatal(err)
}

fmt.Println(resp.Auth.Token)
myMetrics := []influxdb.Metric{
    influxdb.NewRowMetric(
        map[string]interface{}{"memory": 1000, "cpu": 0.93},
        "system-metrics",
        map[string]string{"hostname": "hal9000"},
        time.Date(2018, 3, 4, 5, 6, 7, 8, time.UTC)),
}

// We can now do a write even though we didn't put a token in
if _, err := influx.Write(context.Background(), "my-awesome-bucket", "my-very-awesome-org", myMetrics...); err != nil {
    log.Fatal(err)
}
influx.Close() // close the client after this the client is useless.

Output:

d7odFhI50cR8WcLrbfD1pkVenWy51zEM6WC2Md5McGGTxRbOEi5KS0qrXrTEweiH2z5uQjkNa-0YVmpTQlwM3w==
system-metrics,hostname=hal9000 cpu=0.93,memory=1000i 1520139967000000008

func (*Client) Write Uses

func (c *Client) Write(ctx context.Context, bucket, org string, m ...Metric) (n int, err error)

Write writes metrics to a bucket, and org. It retries intelligently. If the write is too big, it retries again, after breaking the payloads into two requests.

ExampleClient_Write_basic is an example of basic writing to influxdb over http(s). While this is fine in a VPN or VPC, we recommend using TLS/HTTPS if you are sending data over the internet, or anywhere your tokens could be intercepted.

Code:

// just us setting up the server so the example will work.  You will likely have to use the old fasioned way to get an *http.Client and address
// alternatively you can leave the *http.Client nil, and it will intelligently create one with sane defaults.
myHTTPClient, myHTTPInfluxAddress, teardown := setupMockServer()
defer teardown() // we shut down our server at the end of the test, obviously you won't be doing this.
influx, err := influxdb.New(myHTTPInfluxAddress, "mytoken", influxdb.WithHTTPClient(myHTTPClient))
if err != nil {
    panic(err) // error handling here, normally we wouldn't use fmt, but it works for the example
}

// we use client.NewRowMetric for the example because its easy, but if you need extra performance
// it is fine to manually build the []client.Metric{}.
myMetrics := []influxdb.Metric{
    influxdb.NewRowMetric(
        map[string]interface{}{"memory": 1000, "cpu": 0.93},
        "system-metrics",
        map[string]string{"hostname": "hal9000"},
        time.Date(2018, 3, 4, 5, 6, 7, 8, time.UTC)),
    influxdb.NewRowMetric(
        map[string]interface{}{"memory": 1000, "cpu": 0.93},
        "system-metrics",
        map[string]string{"hostname": "hal9000"},
        time.Date(2018, 3, 4, 5, 6, 7, 9, time.UTC)),
}

// The actual write..., this method can be called concurrently.
if _, err := influx.Write(context.Background(), "my-awesome-bucket", "my-very-awesome-org", myMetrics...); err != nil {
    log.Fatal(err) // as above use your own error handling here.
}
influx.Close() // closes the client.  After this the client is useless.

Output:

system-metrics,hostname=hal9000 cpu=0.93,memory=1000i 1520139967000000008
system-metrics,hostname=hal9000 cpu=0.93,memory=1000i 1520139967000000009

Code:

// just us setting up the server so the example will work.  You will likely have to use the old fasioned way to get an *http.Client and address
_, certFileName, keyfileName, myHTTPInfluxAddress, teardown := setupTLSMockserver()
defer teardown() // we shut down our server at the end of the test, obviously you won't be doing this.

certPem, err := ioutil.ReadFile(certFileName)
if err != nil {
    log.Fatal(err)
}
keyPem, err := ioutil.ReadFile(keyfileName)
if err != nil {
    log.Fatal(err)
}
cert, err := tls.X509KeyPair(certPem, keyPem)
if err != nil {
    log.Fatal(err)
}

certPool := x509.NewCertPool()

// read in the ca cert, in our case since we are self-signing, we are using the same cert
caCertPem, err := ioutil.ReadFile(certFileName)
if err != nil {
    log.Fatal(err)
}
certPool.AppendCertsFromPEM(caCertPem)

if err != nil {
    log.Fatal(err)
}
tlsConfig := &tls.Config{
    // Reject any TLS certificate that cannot be validated
    ClientAuth: tls.RequireAndVerifyClientCert,
    // Ensure that we only use our "CA" to validate certificates
    // Force it server side
    Certificates: []tls.Certificate{cert},
    RootCAs:      certPool,
}
tlsConfig.BuildNameToCertificate()

influx, err := influxdb.New(myHTTPInfluxAddress, "mytoken", influxdb.WithHTTPClient(influxdb.HTTPClientWithTLSConfig(tlsConfig)))
if err != nil {
    log.Fatal(err)
}

// we use client.NewRowMetric for the example because its easy, but if you need extra performance
// it is fine to manually build the []client.Metric{}
myMetrics := []influxdb.Metric{
    influxdb.NewRowMetric(
        map[string]interface{}{"memory": 1000, "cpu": 0.93},
        "system-metrics",
        map[string]string{"hostname": "hal9000"},
        time.Date(2018, 3, 4, 5, 6, 7, 8, time.UTC)),
    influxdb.NewRowMetric(
        map[string]interface{}{"memory": 1000, "cpu": 0.93},
        "system-metrics",
        map[string]string{"hostname": "hal9000"},
        time.Date(2018, 3, 4, 5, 6, 7, 9, time.UTC)),
}

// The actual write...
if _, err := influx.Write(context.Background(), "my-awesome-bucket", "my-very-awesome-org", myMetrics...); err != nil {
    log.Fatal(err)
}
influx.Close() // close the client after this the client is useless.

Output:

system-metrics,hostname=hal9000 cpu=0.93,memory=1000i 1520139967000000008
system-metrics,hostname=hal9000 cpu=0.93,memory=1000i 1520139967000000009

type Error Uses

type Error struct {
    Code       string
    Message    string
    Err        string
    Op         string
    Line       *int32
    MaxLength  *int32
    RetryAfter *int32
}

Error is an error returned by a client operation It contains a number of contextual fields which describe the nature and cause of the error

func (*Error) Error Uses

func (e *Error) Error() string

Error returns the string representation of the Error struct

type Field Uses

type Field = lp.Field

Field is just a github.com/influxdata/line-protocol.Field. We alias here to keep abstractions from leaking.

type HTTPConfig Uses

type HTTPConfig struct {
    // Addr should be of the form "http://host:port"
    // or "http://[ipv6-host%zone]:port".
    Addr string

    // Username is the influxdb username, optional.
    Username string

    // Password is the influxdb password, optional.
    Password string

    // UserAgent is the http User Agent, defaults to "InfluxDBClient" plus os and version info.
    UserAgent string

    // Timeout for influxdb writes, if set to zero, it defaults to a 20 second timeout. This is a difference from the influxdb1-client.
    Timeout time.Duration

    // InsecureSkipVerify gets passed to the http client, if true, it will
    // skip https certificate verification. Defaults to false.
    // this currently isn't supported, set on the http client.
    InsecureSkipVerify bool

    // TLSConfig allows the user to set their own TLS config for the HTTP
    // Client. If set, this option overrides InsecureSkipVerify.
    // this currently isn't supported, set on the http client.
    TLSConfig *tls.Config

    // Proxy configures the Proxy function on the HTTP client.
    // this currently isn't supported
    Proxy func(req *http.Request) (*url.URL, error)

    // If HTTPClient is nil, the New Client function will use an http client with sane defaults.
    HTTPClient *http.Client
}

HTTPConfig is an https://github.com/influxdata/influxdb1-client compatible client for setting config options. This is here to make transition to the influxdb2 client easy from the old influxdb 1 client library. It is recommended that you set the options using the With___ functions instead.

type Metric Uses

type Metric = lp.Metric

Metric is just a github.com/influxdata/line-protocol.Metric. We alias here to keep abstractions from leaking.

type Option Uses

type Option struct {
    // contains filtered or unexported fields
}

Option is an option for the client config. If you pass multiple incompatible Options the later one should override.

func WithGZIP Uses

func WithGZIP(n int) Option

WithGZIP returns an option for setting gzip compression level. The default (should this option not be used ) is level 4.

func WithHTTPClient Uses

func WithHTTPClient(h *http.Client) Option

WithHTTPClient returns an option for setting a custom HTTP Client

func WithMaxLineBytes Uses

func WithMaxLineBytes(n int) Option

WithMaxLineBytes returns an option for setting the max length of a line of influx line-protocol in bytes.

func WithNoCompression Uses

func WithNoCompression() Option

WithNoCompression returns an option for writing the data to influxdb without compression.

func WithUserAgent Uses

func WithUserAgent(ua string) Option

WithUserAgent returns an option for setting a custom useragent string.

func WithUserAndPass Uses

func WithUserAndPass(username, password string) Option

WithUserAndPass returns an option for setting a username and password, which generates a session for use. TODO(docmerlin): session logic.

func WithV1Config Uses

func WithV1Config(conf *HTTPConfig) Option

WithV1Config is an option for setting config in a way that makes it easy to convert from the old influxdb1 client config.

type QueryCSVResult Uses

type QueryCSVResult struct {
    io.ReadCloser

    Row      []string
    ColNames []string

    Err error
    // contains filtered or unexported fields
}

QueryCSVResult is the result of a flux query in CSV format

func (*QueryCSVResult) Next Uses

func (q *QueryCSVResult) Next() bool

Next iterates to the next row in the data set. Typically this is called like so:

for q.Next(){
	... // do thing here
}

It will call Close() on the result when it encounters EOF.

func (*QueryCSVResult) Unmarshal Uses

func (q *QueryCSVResult) Unmarshal(x interface{}) error

Unmarshal alows you to easily unmarshal rows of results into your own types.

type RowMetric Uses

type RowMetric struct {
    NameStr string
    Tags    []*lp.Tag
    Fields  []*lp.Field
    TS      time.Time
}

RowMetric is a Metric, that has methods to make it easy to add tags and fields

func NewRowMetric Uses

func NewRowMetric(
    fields map[string]interface{},
    name string,
    tags map[string]string,
    ts time.Time,
) *RowMetric

NewRowMetric creates a *RowMetric from tags, fields and a timestamp.

func (*RowMetric) AddField Uses

func (m *RowMetric) AddField(k string, v interface{})

AddField adds an lp.Field to a metric.

func (*RowMetric) AddTag Uses

func (m *RowMetric) AddTag(k, v string)

AddTag adds an lp.Tag to a metric.

func (*RowMetric) FieldList Uses

func (m *RowMetric) FieldList() []*lp.Field

FieldList returns a slice containing the Fields of a Metric.

func (*RowMetric) Name Uses

func (m *RowMetric) Name() string

Name returns the name of the metric.

func (*RowMetric) SortFields Uses

func (m *RowMetric) SortFields()

SortFields orders the fields of a metric alphnumerically by key.

func (*RowMetric) SortTags Uses

func (m *RowMetric) SortTags()

SortTags orders the tags of a metric alphnumerically by key. This is just here as a helper, to make it easy to keep tags sorted if you are creating a RowMetric manually.

func (*RowMetric) TagList Uses

func (m *RowMetric) TagList() []*lp.Tag

TagList returns a slice containing Tags of a Metric.

func (*RowMetric) Time Uses

func (m *RowMetric) Time() time.Time

Time is the timestamp of a metric.

type SetupRequest Uses

type SetupRequest struct {
    Username           string `json:"username"`
    Password           string `json:"password"`
    Org                string `json:"org"`
    Bucket             string `json:"bucket"`
    RetentionPeriodHrs int    `json:"retentionPeriodHrs"`
}

SetupRequest is a request to setup a new influx instance.

type SetupResult Uses

type SetupResult struct {
    Code    string `json:"code"`
    Message string `json:"message"`
    User    struct {
        Links struct {
            Logs string `json:"logs"`
            Self string `json:"self"`
        }   `json:"links"`
        ID   string `json:"id"`
        Name string `json:"name"`
    }   `json:"user"`
    Bucket struct {
        ID             string `json:"id"`
        OrganizationID string `json:"organizationID"`
        Organization   string `json:"organization"`
        Name           string `json:"name"`
        RetentionRules []struct {
            Type         string `json:"type"`
            EverySeconds int    `json:"everySeconds"`
        }   `json:"retentionRules"`
        Links struct {
            Labels  string `json:"labels"`
            Logs    string `json:"logs"`
            Members string `json:"members"`
            Org     string `json:"org"`
            Owners  string `json:"owners"`
            Self    string `json:"self"`
            Write   string `json:"write"`
        }   `json:"links"`
    }   `json:"bucket"`
    Org struct {
        Links struct {
            Buckets    string `json:"buckets"`
            Dashboards string `json:"dashboards"`
            Labels     string `json:"labels"`
            Logs       string `json:"logs"`
            Members    string `json:"members"`
            Owners     string `json:"owners"`
            Secrets    string `json:"secrets"`
            Self       string `json:"self"`
            Tasks      string `json:"tasks"`
        }   `json:"links"`
        ID   string `json:"id"`
        Name string `json:"name"`
    }   `json:"org"`
    Auth struct {
        ID          string `json:"id"`
        Token       string `json:"token"`
        Status      string `json:"status"`
        Description string `json:"description"`
        OrgID       string `json:"orgID"`
        Org         string `json:"org"`
        UserID      string `json:"userID"`
        User        string `json:"user"`
        Permissions []struct {
            Action   string `json:"action"`
            Resource struct {
                Type string `json:"type"`
            }   `json:"resource"`
        }   `json:"permissions"`
        Links struct {
            Self string `json:"self"`
            User string `json:"user"`
        }   `json:"links"`
    }   `json:"auth"`
}

SetupResult is the result of setting up a new influx instance.

type Tag Uses

type Tag = lp.Tag

Tag is just a github.com/influxdata/line-protocol.Tag. We alias here to keep abstractions from leaking.

Directories

PathSynopsis
generatedCode generated for client DO NOT EDIT.
internal/astPackage ast provides tools for manipulating the flux ast.
internal/gzip
internal/scripts
writerPackage writer contains useful types for buffering, batching and periodically syncing writes onto a provided metric writing client.

Package influxdb imports 25 packages (graph) and is imported by 1 packages. Updated 2019-10-31. Refresh now. Tools for package owners.