Documentation ¶
Overview ¶
Package influxdb2 provides API for using InfluxDB client in Go. It's intended to use with InfluxDB 2 server. WriteAPI, QueryAPI and Health work also with InfluxDB 1.8
Index ¶
- Constants
- func DefaultDialect() *domain.Dialect
- func NewPoint(measurement string, tags map[string]string, fields map[string]interface{}, ...) *write.Point
- func NewPointWithMeasurement(measurement string) *write.Point
- type Client
- type Options
- func (o *Options) AddDefaultTag(key, value string) *Options
- func (o *Options) ApplicationName() string
- func (o *Options) BatchSize() uint
- func (o *Options) ExponentialBase() uint
- func (o *Options) FlushInterval() uint
- func (o *Options) HTTPClient() *nethttp.Client
- func (o *Options) HTTPOptions() *http.Options
- func (o *Options) HTTPRequestTimeout() uint
- func (o *Options) LogLevel() uint
- func (o *Options) MaxRetries() uint
- func (o *Options) MaxRetryInterval() uint
- func (o *Options) MaxRetryTime() uint
- func (o *Options) Precision() time.Duration
- func (o *Options) RetryBufferLimit() uint
- func (o *Options) RetryInterval() uint
- func (o *Options) SetApplicationName(appName string) *Options
- func (o *Options) SetBatchSize(batchSize uint) *Options
- func (o *Options) SetExponentialBase(exponentialBase uint) *Options
- func (o *Options) SetFlushInterval(flushIntervalMs uint) *Options
- func (o *Options) SetHTTPClient(c *nethttp.Client) *Options
- func (o *Options) SetHTTPRequestTimeout(httpRequestTimeout uint) *Options
- func (o *Options) SetLogLevel(logLevel uint) *Options
- func (o *Options) SetMaxRetries(maxRetries uint) *Options
- func (o *Options) SetMaxRetryInterval(maxRetryIntervalMs uint) *Options
- func (o *Options) SetMaxRetryTime(maxRetryTimeMs uint) *Options
- func (o *Options) SetPrecision(precision time.Duration) *Options
- func (o *Options) SetRetryBufferLimit(retryBufferLimit uint) *Options
- func (o *Options) SetRetryInterval(retryIntervalMs uint) *Options
- func (o *Options) SetTLSConfig(tlsConfig *tls.Config) *Options
- func (o *Options) SetUseGZip(useGZip bool) *Options
- func (o *Options) TLSConfig() *tls.Config
- func (o *Options) UseGZip() bool
- func (o *Options) WriteOptions() *write.Options
Examples ¶
Constants ¶
const (
// Version defines current version
Version = "2.14.0"
)
Variables ¶
This section is empty.
Functions ¶
func DefaultDialect ¶
DefaultDialect return flux query Dialect with full annotations (datatype, group, default), header and comma char as a delimiter
func NewPoint ¶
func NewPoint( measurement string, tags map[string]string, fields map[string]interface{}, ts time.Time, ) *write.Point
NewPoint creates a Point from measurement name, tags, fields and a timestamp.
func NewPointWithMeasurement ¶
NewPointWithMeasurement creates a empty Point Use AddTag and AddField to fill point with data
Types ¶
type Client ¶
type Client interface { // Setup sends request to initialise new InfluxDB server with user, org and bucket, and data retention period // and returns details about newly created entities along with the authorization object. // Retention period of zero will result to infinite retention. Setup(ctx context.Context, username, password, org, bucket string, retentionPeriodHours int) (*domain.OnboardingResponse, error) // SetupWithToken sends request to initialise new InfluxDB server with user, org and bucket, data retention period and token // and returns details about newly created entities along with the authorization object. // Retention period of zero will result to infinite retention. SetupWithToken(ctx context.Context, username, password, org, bucket string, retentionPeriodHours int, token string) (*domain.OnboardingResponse, error) // Ready returns InfluxDB uptime info of server. It doesn't validate authentication params. Ready(ctx context.Context) (*domain.Ready, error) // Health returns an InfluxDB server health check result. Read the HealthCheck.Status field to get server status. // Health doesn't validate authentication params. Health(ctx context.Context) (*domain.HealthCheck, error) // Ping validates whether InfluxDB server is running. It doesn't validate authentication params. Ping(ctx context.Context) (bool, error) // Close ensures all ongoing asynchronous write clients finish. // Also closes all idle connections, in case of HTTP client was created internally. Close() // Options returns the options associated with client Options() *Options // ServerURL returns the url of the server url client talks to ServerURL() string // HTTPService returns underlying HTTP service object used by client HTTPService() http.Service // WriteAPI returns the asynchronous, non-blocking, Write client. // Ensures using a single WriteAPI instance for each org/bucket pair. WriteAPI(org, bucket string) api.WriteAPI // WriteAPIBlocking returns the synchronous, blocking, Write client. // Ensures using a single WriteAPIBlocking instance for each org/bucket pair. WriteAPIBlocking(org, bucket string) api.WriteAPIBlocking // QueryAPI returns Query client. // Ensures using a single QueryAPI instance each org. QueryAPI(org string) api.QueryAPI // AuthorizationsAPI returns Authorizations API client. AuthorizationsAPI() api.AuthorizationsAPI // OrganizationsAPI returns Organizations API client OrganizationsAPI() api.OrganizationsAPI // UsersAPI returns Users API client. UsersAPI() api.UsersAPI // DeleteAPI returns Delete API client DeleteAPI() api.DeleteAPI // BucketsAPI returns Buckets API client BucketsAPI() api.BucketsAPI // LabelsAPI returns Labels API client LabelsAPI() api.LabelsAPI // TasksAPI returns Tasks API client TasksAPI() api.TasksAPI APIClient() *domain.Client }
Client provides API to communicate with InfluxDBServer. There two APIs for writing, WriteAPI and WriteAPIBlocking. WriteAPI provides asynchronous, non-blocking, methods for writing time series data. WriteAPIBlocking provides blocking methods for writing time series data.
Example (CheckAPICall) ¶
// This example shows how to perform custom server API invocation for checks API // Create client. You need an admin token for creating DBRP mapping client := influxdb2.NewClient("http://localhost:8086", "my-token") // Always close client at the end defer client.Close() ctx := context.Background() // Create a new threshold check greater := domain.GreaterThreshold{} greater.Value = 10.0 lc := domain.CheckStatusLevelCRIT greater.Level = &lc greater.AllValues = &[]bool{true}[0] lesser := domain.LesserThreshold{} lesser.Value = 1.0 lo := domain.CheckStatusLevelOK lesser.Level = &lo rang := domain.RangeThreshold{} rang.Min = 3.0 rang.Max = 8.0 lw := domain.CheckStatusLevelWARN rang.Level = &lw thresholds := []domain.Threshold{&greater, &lesser, &rang} // Get organization where check will be created org, err := client.OrganizationsAPI().FindOrganizationByName(ctx, "my-org") if err != nil { panic(err) } // Prepare necessary parameters msg := "Check: ${ r._check_name } is: ${ r._level }" flux := `from(bucket: "foo") |> range(start: -1d, stop: now()) |> aggregateWindow(every: 1m, fn: mean) |> filter(fn: (r) => r._field == "usage_user") |> yield()` every := "1h" offset := "0s" c := domain.ThresholdCheck{ CheckBaseExtend: domain.CheckBaseExtend{ CheckBase: domain.CheckBase{ Name: "My threshold check", OrgID: *org.Id, Query: domain.DashboardQuery{Text: &flux}, Status: domain.TaskStatusTypeActive, }, Every: &every, Offset: &offset, StatusMessageTemplate: &msg, }, Thresholds: &thresholds, } params := domain.CreateCheckAllParams{ Body: &c, } // Call checks API using internal API client check, err := client.APIClient().CreateCheck(context.Background(), ¶ms) if err != nil { panic(err) } // Optionally verify type if check.Type() != string(domain.ThresholdCheckTypeThreshold) { panic("Check type is not threshold") } // Cast check to threshold check thresholdCheck := check.(*domain.ThresholdCheck) fmt.Printf("Created threshold check with id %s\n", *thresholdCheck.Id)
Output:
Example (CustomServerAPICall) ¶
// This example shows how to perform custom server API invocation for any endpoint // Here we will create a DBRP mapping which allows using buckets in legacy write and query (InfluxQL) endpoints // Create client. You need an admin token for creating DBRP mapping client := influxdb2.NewClient("http://localhost:8086", "my-token") // Always close client at the end defer client.Close() // Get generated client for server API calls apiClient := client.APIClient() ctx := context.Background() // Get a bucket we would like to query using InfluxQL b, err := client.BucketsAPI().FindBucketByName(ctx, "my-bucket") if err != nil { panic(err) } // Get an organization that will own the mapping o, err := client.OrganizationsAPI().FindOrganizationByName(ctx, "my-org") if err != nil { panic(err) } yes := true // Fill required fields of the DBRP struct dbrp := domain.DBRPCreate{ BucketID: *b.Id, Database: "my-bucket", Default: &yes, OrgID: o.Id, RetentionPolicy: "autogen", } params := &domain.PostDBRPAllParams{ Body: domain.PostDBRPJSONRequestBody(dbrp), } // Call server API newDbrp, err := apiClient.PostDBRP(ctx, params) if err != nil { panic(err) } // Check generated response errors fmt.Printf("Created DBRP: %#v\n", newDbrp)
Output:
Example (CustomUserAgentHeader) ¶
package main import ( "context" "fmt" "net/http" "github.com/influxdata/influxdb-client-go/v2" ihttp "github.com/influxdata/influxdb-client-go/v2/api/http" ) // UserAgentSetter is the implementation of Doer interface for setting User-Agent header type UserAgentSetter struct { UserAgent string RequestDoer ihttp.Doer } // Do fulfills the Doer interface func (u *UserAgentSetter) Do(req *http.Request) (*http.Response, error) { // Set User-Agent header to request req.Header.Set("User-Agent", u.UserAgent) // Call original Doer to proceed with request return u.RequestDoer.Do(req) } func main() { // Set custom Doer to HTTPOptions opts := influxdb2.DefaultOptions() opts.HTTPOptions().SetHTTPDoer(&UserAgentSetter{ UserAgent: "NetMonitor/1.1", RequestDoer: http.DefaultClient, }) //Create client with customized options client := influxdb2.NewClientWithOptions("http://localhost:8086", "my-token", opts) // Always close client at the end defer client.Close() // Issue a call with custom User-Agent header resp, err := client.Ping(context.Background()) if err != nil { panic(err) } if resp { fmt.Println("Server is up") } else { fmt.Println("Server is down") } }
Output:
Example (NewClient) ¶
// Create a new client using an InfluxDB server base URL and an authentication token client := influxdb2.NewClient("http://localhost:8086", "my-token") // Always close client at the end defer client.Close()
Output:
Example (NewClientWithOptions) ¶
// Create a new client using an InfluxDB server base URL and an authentication token // Create client and set batch size to 20 client := influxdb2.NewClientWithOptions("http://localhost:8086", "my-token", influxdb2.DefaultOptions().SetBatchSize(20)) // Always close client at the end defer client.Close()
Output:
func NewClient ¶
NewClient creates Client for connecting to given serverURL with provided authentication token, with the default options. serverURL is the InfluxDB server base URL, e.g. http://localhost:8086, authToken is an authentication token. It can be empty in case of connecting to newly installed InfluxDB server, which has not been set up yet. In such case, calling Setup() will set the authentication token.
func NewClientWithOptions ¶
NewClientWithOptions creates Client for connecting to given serverURL with provided authentication token and configured with custom Options. serverURL is the InfluxDB server base URL, e.g. http://localhost:8086, authToken is an authentication token. It can be empty in case of connecting to newly installed InfluxDB server, which has not been set up yet. In such case, calling Setup() will set authentication token
type Options ¶
type Options struct {
// contains filtered or unexported fields
}
Options holds configuration properties for communicating with InfluxDB server
func DefaultOptions ¶
func DefaultOptions() *Options
DefaultOptions returns Options object with default values
func (*Options) AddDefaultTag ¶
AddDefaultTag adds a default tag. DefaultTags are added to each written point. If a tag with the same key already exist it is overwritten. If a point already defines such a tag, it is left unchanged
func (*Options) ApplicationName ¶ added in v2.12.0
ApplicationName returns application name used in the User-Agent HTTP header
func (*Options) ExponentialBase ¶ added in v2.5.0
ExponentialBase returns the base for the exponential retry delay. Default 2.
func (*Options) FlushInterval ¶
FlushInterval returns flush interval in ms
func (*Options) HTTPClient ¶
HTTPClient returns the http.Client that is configured to be used for HTTP requests. It will return the one that has been set using SetHTTPClient or it will construct a default client using the other configured options.
func (*Options) HTTPOptions ¶
HTTPOptions returns HTTP related options
func (*Options) HTTPRequestTimeout ¶
HTTPRequestTimeout returns HTTP request timeout
func (*Options) MaxRetries ¶
MaxRetries returns maximum count of retry attempts of failed writes, default 5.
func (*Options) MaxRetryInterval ¶
MaxRetryInterval returns the maximum delay between each retry attempt in milliseconds, default 125,000.
func (*Options) MaxRetryTime ¶ added in v2.5.0
MaxRetryTime returns the maximum total retry timeout in millisecond, default 180,000.
func (*Options) RetryBufferLimit ¶
RetryBufferLimit returns retry buffer limit
func (*Options) RetryInterval ¶
RetryInterval returns the retry interval in ms
func (*Options) SetApplicationName ¶ added in v2.12.0
SetApplicationName sets an application name to the User-Agent HTTP header
func (*Options) SetBatchSize ¶
SetBatchSize sets number of points sent in single request
func (*Options) SetExponentialBase ¶ added in v2.5.0
SetExponentialBase sets the base for the exponential retry delay.
func (*Options) SetFlushInterval ¶
SetFlushInterval sets flush interval in ms in which is buffer flushed if it has not been already written
func (*Options) SetHTTPClient ¶
SetHTTPClient will configure the http.Client that is used for HTTP requests. If set to nil, an HTTPClient will be generated.
Setting the HTTPClient will cause the other HTTP options to be ignored. In case of UsersAPI.SignIn() is used, HTTPClient.Jar will be used for storing session cookie.
func (*Options) SetHTTPRequestTimeout ¶
SetHTTPRequestTimeout sets HTTP request timeout in sec
func (*Options) SetLogLevel ¶
SetLogLevel set level to filter log messages. Each level mean to log all categories bellow. Default is ErrorLevel. There are four level constant int the log package in this library:
- ErrorLevel
- WarningLevel
- InfoLevel
- DebugLevel
The DebugLevel will print also content of writen batches, queries. The InfoLevel prints HTTP requests info, among others. Set log.Log to nil in order to completely disable logging.
func (*Options) SetMaxRetries ¶
SetMaxRetries sets maximum count of retry attempts of failed writes. Setting zero value disables retry strategy.
func (*Options) SetMaxRetryInterval ¶
SetMaxRetryInterval sets the maximum delay between each retry attempt in millisecond.
func (*Options) SetMaxRetryTime ¶ added in v2.5.0
SetMaxRetryTime sets the maximum total retry timeout in millisecond.
func (*Options) SetPrecision ¶
SetPrecision sets time precision to use in writes for timestamp. In unit of duration: time.Nanosecond, time.Microsecond, time.Millisecond, time.Second
func (*Options) SetRetryBufferLimit ¶
SetRetryBufferLimit sets maximum number of points to keep for retry. Should be multiple of BatchSize.
func (*Options) SetRetryInterval ¶
SetRetryInterval sets retry interval in ms, which is set if not sent by server
func (*Options) SetTLSConfig ¶
SetTLSConfig sets TLS configuration for secure connection
func (*Options) SetUseGZip ¶
SetUseGZip specifies whether to use GZip compression in write requests.
func (*Options) WriteOptions ¶
WriteOptions returns write related options
Directories ¶
Path | Synopsis |
---|---|
Package api provides clients for InfluxDB server APIs.
|
Package api provides clients for InfluxDB server APIs. |
http
Package http provides HTTP servicing related code.
|
Package http provides HTTP servicing related code. |
query
Package query defined types for representing flux query result
|
Package query defined types for representing flux query result |
write
Package write provides the Point struct
|
Package write provides the Point struct |
Package domain provides primitives to interact with the openapi HTTP API.
|
Package domain provides primitives to interact with the openapi HTTP API. |
internal
|
|
examples
Package examples contains fake client with the same interface as real client to overcome import-cycle problem to allow real E2E examples for apis in this package
|
Package examples contains fake client with the same interface as real client to overcome import-cycle problem to allow real E2E examples for apis in this package |
gzip
Package gzip provides GZip related functionality
|
Package gzip provides GZip related functionality |
http
Package http hold internal HTTP related stuff
|
Package http hold internal HTTP related stuff |
log
Package log provides internal logging infrastructure
|
Package log provides internal logging infrastructure |
test
Package test provides shared test utils
|
Package test provides shared test utils |
write
Package write provides service and its stuff
|
Package write provides service and its stuff |
Package log defines Logging API.
|
Package log defines Logging API. |