client

package module
v0.0.0-...-fc22c7d Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 9, 2019 License: MIT Imports: 16 Imported by: 0

README

influxdb1-clientv2

influxdb1-clientv2 is the current Go client API for InfluxDB 1.x. A Go client for the 2.0 API will be coming soon.

InfluxDB is an open-source distributed time series database, find more about InfluxDB at https://docs.influxdata.com/influxdb/latest

Usage

To import into your Go project, run the following command in your terminal: go get github.com/influxdata/influxdb1-client/v2 Then, in your import declaration section of your Go file, paste the following: import "github.com/influxdata/influxdb1-client/v2"

If you get the error build github.com/user/influx: cannot find module for path github.com/influxdata/influxdb1-client/v2 when trying to build: change your import to:

import(
	_ "github.com/influxdata/influxdb1-client" // this is important because of the bug in go mod
	client "github.com/influxdata/influxdb1-client/v2"
)

Example

The following example creates a new client to the InfluxDB host on localhost:8086 and runs a query for the measurement cpu_load from the mydb database.

func ExampleClient_query() {
	c, err := client.NewHTTPClient(client.HTTPConfig{
		Addr: "http://localhost:8086",
	})
	if err != nil {
		fmt.Println("Error creating InfluxDB Client: ", err.Error())
	}
	defer c.Close()

	q := client.NewQuery("SELECT count(value) FROM cpu_load", "mydb", "")
	if response, err := c.Query(q); err == nil && response.Error() == nil {
		fmt.Println(response.Results)
	}
}

Documentation

Overview

Package client implements a now-deprecated client for InfluxDB; use github.com/influxdata/influxdb1-client/v2 instead.

Index

Examples

Constants

View Source
const (
	// DefaultHost is the default host used to connect to an InfluxDB instance
	DefaultHost = "localhost"

	// DefaultPort is the default port used to connect to an InfluxDB instance
	DefaultPort = 8086

	// DefaultTimeout is the default connection timeout used to connect to an InfluxDB instance
	DefaultTimeout = 0
)
View Source
const (
	// ConsistencyOne requires at least one data node acknowledged a write.
	ConsistencyOne = "one"

	// ConsistencyAll requires all data nodes to acknowledge a write.
	ConsistencyAll = "all"

	// ConsistencyQuorum requires a quorum of data nodes to acknowledge a write.
	ConsistencyQuorum = "quorum"

	// ConsistencyAny allows for hinted hand off, potentially no write happened yet.
	ConsistencyAny = "any"
)

Variables

This section is empty.

Functions

func EpochToTime

func EpochToTime(epoch int64, precision string) (time.Time, error)

EpochToTime takes a unix epoch time and uses precision to return back a time.Time

func ParseConnectionString

func ParseConnectionString(path string, ssl bool) (url.URL, error)

ParseConnectionString will parse a string to create a valid connection URL

func SetPrecision

func SetPrecision(t time.Time, precision string) time.Time

SetPrecision will round a time to the specified precision

Types

type BatchPoints

type BatchPoints struct {
	Points           []Point           `json:"points,omitempty"`
	Database         string            `json:"database,omitempty"`
	RetentionPolicy  string            `json:"retentionPolicy,omitempty"`
	Tags             map[string]string `json:"tags,omitempty"`
	Time             time.Time         `json:"time,omitempty"`
	Precision        string            `json:"precision,omitempty"`
	WriteConsistency string            `json:"-"`
}

BatchPoints is used to send batched data in a single write. Database and Points are required If no retention policy is specified, it will use the databases default retention policy. If tags are specified, they will be "merged" with all points. If a point already has that tag, it will be ignored. If time is specified, it will be applied to any point with an empty time. Precision can be specified if the time is in epoch format (integer). Valid values for Precision are n, u, ms, s, m, and h

func (*BatchPoints) UnmarshalJSON

func (bp *BatchPoints) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes the data into the BatchPoints struct

type ChunkedResponse

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

ChunkedResponse represents a response from the server that uses chunking to stream the output.

func NewChunkedResponse

func NewChunkedResponse(r io.Reader) *ChunkedResponse

NewChunkedResponse reads a stream and produces responses from the stream.

func (*ChunkedResponse) NextResponse

func (r *ChunkedResponse) NextResponse() (*Response, error)

NextResponse reads the next line of the stream and returns a response.

type Client

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

Client is used to make calls to the server.

func NewClient

func NewClient(c Config) (*Client, error)

NewClient will instantiate and return a connected client to issue commands to the server.

Example
package main

import (
	"fmt"
	"log"
	"net/url"
	"os"

	client "github.com/influxdata/influxdb1-client"
)

func main() {
	host, err := url.Parse(fmt.Sprintf("http://%s:%d", "localhost", 8086))
	if err != nil {
		log.Fatal(err)
	}

	// NOTE: this assumes you've setup a user and have setup shell env variables,
	// namely INFLUX_USER/INFLUX_PWD. If not just omit Username/Password below.
	conf := client.Config{
		URL:      *host,
		Username: os.Getenv("INFLUX_USER"),
		Password: os.Getenv("INFLUX_PWD"),
	}
	con, err := client.NewClient(conf)
	if err != nil {
		log.Fatal(err)
	}
	log.Println("Connection", con)
}
Output:

func (*Client) Addr

func (c *Client) Addr() string

Addr provides the current url as a string of the server the client is connected to.

func (*Client) Ping

func (c *Client) Ping() (time.Duration, string, error)

Ping will check to see if the server is up Ping returns how long the request took, the version of the server it connected to, and an error if one occurred.

Example
package main

import (
	"fmt"
	"log"
	"net/url"

	client "github.com/influxdata/influxdb1-client"
)

func main() {
	host, err := url.Parse(fmt.Sprintf("http://%s:%d", "localhost", 8086))
	if err != nil {
		log.Fatal(err)
	}
	con, err := client.NewClient(client.Config{URL: *host})
	if err != nil {
		log.Fatal(err)
	}

	dur, ver, err := con.Ping()
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("Happy as a hippo! %v, %s", dur, ver)
}
Output:

func (*Client) Query

func (c *Client) Query(q Query) (*Response, error)

Query sends a command to the server and returns the Response

Example
package main

import (
	"fmt"
	"log"
	"net/url"

	client "github.com/influxdata/influxdb1-client"
)

func main() {
	host, err := url.Parse(fmt.Sprintf("http://%s:%d", "localhost", 8086))
	if err != nil {
		log.Fatal(err)
	}
	con, err := client.NewClient(client.Config{URL: *host})
	if err != nil {
		log.Fatal(err)
	}

	q := client.Query{
		Command:  "select count(value) from shapes",
		Database: "square_holes",
	}
	if response, err := con.Query(q); err == nil && response.Error() == nil {
		log.Println(response.Results)
	}
}
Output:

func (*Client) QueryContext

func (c *Client) QueryContext(ctx context.Context, q Query) (*Response, error)

QueryContext sends a command to the server and returns the Response It uses a context that can be cancelled by the command line client

func (*Client) SetAuth

func (c *Client) SetAuth(u, p string)

SetAuth will update the username and passwords

func (*Client) SetPrecision

func (c *Client) SetPrecision(precision string)

SetPrecision will update the precision

func (*Client) Write

func (c *Client) Write(bp BatchPoints) (*Response, error)

Write takes BatchPoints and allows for writing of multiple points with defaults If successful, error is nil and Response is nil If an error occurs, Response may contain additional information if populated.

Example
package main

import (
	"fmt"
	"log"
	"math/rand"
	"net/url"
	"strconv"
	"time"

	client "github.com/influxdata/influxdb1-client"
)

func main() {
	host, err := url.Parse(fmt.Sprintf("http://%s:%d", "localhost", 8086))
	if err != nil {
		log.Fatal(err)
	}
	con, err := client.NewClient(client.Config{URL: *host})
	if err != nil {
		log.Fatal(err)
	}

	var (
		shapes     = []string{"circle", "rectangle", "square", "triangle"}
		colors     = []string{"red", "blue", "green"}
		sampleSize = 1000
		pts        = make([]client.Point, sampleSize)
	)

	rand.Seed(42)
	for i := 0; i < sampleSize; i++ {
		pts[i] = client.Point{
			Measurement: "shapes",
			Tags: map[string]string{
				"color": strconv.Itoa(rand.Intn(len(colors))),
				"shape": strconv.Itoa(rand.Intn(len(shapes))),
			},
			Fields: map[string]interface{}{
				"value": rand.Intn(sampleSize),
			},
			Time:      time.Now(),
			Precision: "s",
		}
	}

	bps := client.BatchPoints{
		Points:          pts,
		Database:        "BumbeBeeTuna",
		RetentionPolicy: "default",
	}
	_, err = con.Write(bps)
	if err != nil {
		log.Fatal(err)
	}
}
Output:

func (*Client) WriteLineProtocol

func (c *Client) WriteLineProtocol(data, database, retentionPolicy, precision, writeConsistency string) (*Response, error)

WriteLineProtocol takes a string with line returns to delimit each write If successful, error is nil and Response is nil If an error occurs, Response may contain additional information if populated.

type Config

type Config struct {
	URL              url.URL
	UnixSocket       string
	Username         string
	Password         string
	UserAgent        string
	Timeout          time.Duration
	Precision        string
	WriteConsistency string
	UnsafeSsl        bool
	Proxy            func(req *http.Request) (*url.URL, error)
	TLS              *tls.Config
}

Config is used to specify what server to connect to. URL: The URL of the server connecting to. Username/Password are optional. They will be passed via basic auth if provided. UserAgent: If not provided, will default "InfluxDBClient", Timeout: If not provided, will default to 0 (no timeout)

func NewConfig

func NewConfig() Config

NewConfig will create a config to be used in connecting to the client

type Message

type Message struct {
	Level string `json:"level,omitempty"`
	Text  string `json:"text,omitempty"`
}

Message represents a user message.

type Point

type Point struct {
	Measurement string
	Tags        map[string]string
	Time        time.Time
	Fields      map[string]interface{}
	Precision   string
	Raw         string
}

Point defines the fields that will be written to the database Measurement, Time, and Fields are required Precision can be specified if the time is in epoch format (integer). Valid values for Precision are n, u, ms, s, m, and h

func (*Point) MarshalJSON

func (p *Point) MarshalJSON() ([]byte, error)

MarshalJSON will format the time in RFC3339Nano Precision is also ignored as it is only used for writing, not reading Or another way to say it is we always send back in nanosecond precision

func (*Point) MarshalString

func (p *Point) MarshalString() string

MarshalString renders string representation of a Point with specified precision. The default precision is nanoseconds.

func (*Point) UnmarshalJSON

func (p *Point) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes the data into the Point struct

type Query

type Query struct {
	Command  string
	Database string

	// RetentionPolicy tells the server which retention policy to use by default.
	// This option is only effective when querying a server of version 1.6.0 or later.
	RetentionPolicy string

	// Chunked tells the server to send back chunked responses. This places
	// less load on the server by sending back chunks of the response rather
	// than waiting for the entire response all at once.
	Chunked bool

	// ChunkSize sets the maximum number of rows that will be returned per
	// chunk. Chunks are either divided based on their series or if they hit
	// the chunk size limit.
	//
	// Chunked must be set to true for this option to be used.
	ChunkSize int

	// NodeID sets the data node to use for the query results. This option only
	// has any effect in the enterprise version of the software where there can be
	// more than one data node and is primarily useful for analyzing differences in
	// data. The default behavior is to automatically select the appropriate data
	// nodes to retrieve all of the data. On a database where the number of data nodes
	// is greater than the replication factor, it is expected that setting this option
	// will only retrieve partial data.
	NodeID int
}

Query is used to send a command to the server. Both Command and Database are required.

type Response

type Response struct {
	Results []Result
	Err     error
}

Response represents a list of statement results.

func (*Response) Error

func (r *Response) Error() error

Error returns the first error from any statement. Returns nil if no errors occurred on any statements.

func (*Response) MarshalJSON

func (r *Response) MarshalJSON() ([]byte, error)

MarshalJSON encodes the response into JSON.

func (*Response) UnmarshalJSON

func (r *Response) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes the data into the Response struct

type Result

type Result struct {
	Series   []models.Row
	Messages []*Message
	Err      error
}

Result represents a resultset returned from a single statement.

func (*Result) MarshalJSON

func (r *Result) MarshalJSON() ([]byte, error)

MarshalJSON encodes the result into JSON.

func (*Result) UnmarshalJSON

func (r *Result) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes the data into the Result struct

Directories

Path Synopsis
Package models implements basic objects used throughout the TICK stack.
Package models implements basic objects used throughout the TICK stack.
pkg
escape
Package escape contains utilities for escaping parts of InfluxQL and InfluxDB line protocol.
Package escape contains utilities for escaping parts of InfluxQL and InfluxDB line protocol.
Package client (v2) is the current official Go client for InfluxDB.
Package client (v2) is the current official Go client for InfluxDB.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL