influxdb

package module
v2.0.8 Latest Latest
Warning

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

Go to latest
Published: Aug 13, 2021 License: MIT Imports: 28 Imported by: 11

README ¶

InfluxDB CircleCI

Slack Status

InfluxDB is an open source time series platform. This includes APIs for storing and querying data, processing it in the background for ETL or monitoring and alerting purposes, user dashboards, and visualizing and exploring the data and more. The master branch on this repo now represents the latest InfluxDB, which now includes functionality for Kapacitor (background processing) and Chronograf (the UI) all in a single binary.

The list of InfluxDB Client Libraries that are compatible with the latest version can be found in our documentation.

If you are looking for the 1.x line of releases, there are branches for each minor version as well as a master-1.x branch that will contain the code for the next 1.x release. The master-1.x working branch is here. The InfluxDB 1.x Go Client can be found here.

Installing from Source

We have nightly and versioned Docker images, Debian packages, RPM packages, and tarballs of InfluxDB available at the InfluxData downloads page. We also provide the influx command line interface (CLI) client as a separate binary available at the same location.

Building From Source

This project requires Go 1.15 and Go module support.

Set GO111MODULE=on or build the project outside of your GOPATH for it to succeed.

The project also requires a recent stable version of Rust. We recommend using rustup to install Rust.

If you are getting an error loading module requirements error with bzr executable file not found in $PATH” on make, then you need to ensure you have bazaar, protobuf, and yarn installed.

  • OSX: brew install bazaar protobuf yarn
  • Linux (Arch): pacman -S bzr protobuf yarn
  • Linux (Ubuntu): apt install bzr protobuf-compiler libprotobuf-dev yarnpkg

NB: For RedHat, there are some extra steps:

  1. You must enable the EPEL
  2. You must add the yarn repository

For information about modules, please refer to the wiki.

A successful make run results in two binaries, with platform-dependent paths:

$ make
...
env GO111MODULE=on go build -tags 'assets ' -o bin/$(uname -s | tr '[:upper:]' '[:lower:]')/influx ./cmd/influx
env GO111MODULE=on go build -tags 'assets ' -o bin/$(uname -s | tr '[:upper:]' '[:lower:]')/influxd ./cmd/influxd

influxd is the InfluxDB service. influx is the CLI management tool.

Start the service. Logs to stdout by default:

$ bin/$(uname -s | tr '[:upper:]' '[:lower:]')/influxd
Building with the go command

The Makefile provides a wrapper around configuring the utilities for building influxdb. For those wanting to use the go command directly, one of two things can be done.

First, the env script is located in the root of the repository. This script can be used to execute go commands with the appropriate environment configuration.

$ ./env go build ./cmd/influxd

Another method is to configure the pkg-config utility. Follow the instructions here to install and configure pkg-config and then the normal go commands will work.

The first step is to install the pkg-config command.

# On Debian/Ubuntu
$ sudo apt-get install -y clang pkg-config
# On Mac OS X with Homebrew
$ brew install pkg-config

Install the pkg-config wrapper utility of the same name to a different path that is earlier in the PATH.

# Install the pkg-config wrapper utility
$ go build -o ~/go/bin/ github.com/influxdata/pkg-config
# Ensure the GOBIN directory is on your PATH
$ export PATH=$HOME/go/bin:${PATH}
$ which -a pkg-config
/home/user/go/bin/pkg-config
/usr/bin/pkg-config

Then all go build commands should work.

$ go build ./cmd/influxd
$ go test ./...

Getting Started

For a complete getting started guide, please see our full online documentation site.

To write and query data or use the API in any way, you'll need to first create a user, credentials, organization and bucket. Everything in InfluxDB is organized under a concept of an organization. The API is designed to be multi-tenant. Buckets represent where you store time series data. They're synonymous with what was previously in InfluxDB 1.x a database and retention policy.

The simplest way to get set up is to point your browser to http://localhost:8086 and go through the prompts.

You can also get set up from the CLI using the command influx setup:

$ bin/$(uname -s | tr '[:upper:]' '[:lower:]')/influx setup
Welcome to InfluxDB 2.0!
Please type your primary username: marty

Please type your password: 

Please type your password again: 

Please type your primary organization name.: InfluxData

Please type your primary bucket name.: telegraf

Please type your retention period in hours.
Or press ENTER for infinite.: 72


You have entered:
  Username:          marty
  Organization:      InfluxData
  Bucket:            telegraf
  Retention Period:  72 hrs
Confirm? (y/n): y

UserID                  Username        Organization    Bucket
033a3f2c5ccaa000        marty           InfluxData      Telegraf
Your token has been stored in /Users/marty/.influxdbv2/credentials

You can run this command non-interactively using the -f, --force flag if you are automating the setup. Some added flags can help:

$ bin/$(uname -s | tr '[:upper:]' '[:lower:]')/influx setup \
--username marty \
--password F1uxKapacit0r85 \
--org InfluxData \
--bucket telegraf \
--retention 168 \
--token where-were-going-we-dont-need-roads \
--force

Once setup is complete, a configuration profile is created to allow you to interact with your local InfluxDB without passing in credentials each time. You can list and manage those profiles using the influx config command.

$ bin/$(uname -s | tr '[:upper:]' '[:lower:]')/influx config
Active	Name	URL			            Org
*	    default	http://localhost:8086	InfluxData

Writing Data

Write to measurement m, with tag v=2, in bucket telegraf, which belongs to organization InfluxData:

$ bin/$(uname -s | tr '[:upper:]' '[:lower:]')/influx write --bucket telegraf --precision s "m v=2 $(date +%s)"

Since you have a default profile set up, you can omit the Organization and Token from the command.

Write the same point using curl:

curl --header "Authorization: Token $(bin/$(uname -s | tr '[:upper:]' '[:lower:]')/influx auth list --json | jq -r '.[0].token')" \
--data-raw "m v=2 $(date +%s)" \
"http://localhost:8086/api/v2/write?org=InfluxData&bucket=telegraf&precision=s"

Read that back with a simple Flux query:

$ bin/$(uname -s | tr '[:upper:]' '[:lower:]')/influx query 'from(bucket:"telegraf") |> range(start:-1h)'
Result: _result
Table: keys: [_start, _stop, _field, _measurement]
                   _start:time                      _stop:time           _field:string     _measurement:string                      _time:time                  _value:float
------------------------------  ------------------------------  ----------------------  ----------------------  ------------------------------  ----------------------------
2019-12-30T22:19:39.043918000Z  2019-12-30T23:19:39.043918000Z                       v                       m  2019-12-30T23:17:02.000000000Z                             2

Use the -r, --raw option to return the raw flux response from the query. This is useful for moving data from one instance to another as the influx write command can accept the Flux response using the --format csv option.

Introducing Flux

Flux is an MIT-licensed data scripting language (previously named IFQL) used for querying time series data from InfluxDB. The source for Flux is available on GitHub. Learn more about Flux from CTO Paul Dix's presentation.

Contributing to the Project

InfluxDB is an MIT licensed open source project and we love our community. The fastest way to get something fixed is to open a PR. Check out our contributing guide if you're interested in helping out. Also, join us on our Community Slack Workspace if you have questions or comments for our engineering teams.

CI and Static Analysis

CI

All pull requests will run through CI, which is currently hosted by Circle. Community contributors should be able to see the outcome of this process by looking at the checks on their PR. Please fix any issues to ensure a prompt review from members of the team.

The InfluxDB project is used internally in a number of proprietary InfluxData products, and as such, PRs and changes need to be tested internally. This can take some time, and is not really visible to community contributors.

Static Analysis

This project uses the following static analysis tools. Failure during the running of any of these tools results in a failed build. Generally, code must be adjusted to satisfy these tools, though there are exceptions.

  • go vet checks for Go code that should be considered incorrect.
  • go fmt checks that Go code is correctly formatted.
  • go mod tidy ensures that the source code and go.mod agree.
  • staticcheck checks for things like: unused code, code that can be simplified, code that is incorrect and code that will have performance issues.
staticcheck

If your PR fails staticcheck it is easy to dig into why it failed, and also to fix the problem. First, take a look at the error message in Circle under the staticcheck build section, e.g.,

tsdb/tsm1/encoding.gen.go:1445:24: func BooleanValues.assertOrdered is unused (U1000)
tsdb/tsm1/encoding.go:172:7: receiver name should not be an underscore, omit the name if it is unused (ST1006)

Next, go and take a look here for some clarification on the error code that you have received, e.g., U1000. The docs will tell you what's wrong, and often what you need to do to fix the issue.

Generated Code

Sometimes generated code will contain unused code or occasionally that will fail a different check. staticcheck allows for entire files to be ignored, though it's not ideal. A linter directive, in the form of a comment, must be placed within the generated file. This is problematic because it will be erased if the file is re-generated. Until a better solution comes about, below is the list of generated files that need an ignores comment. If you re-generate a file and find that staticcheck has failed, please see this list below for what you need to put back:

File Comment
query/promql/promql.go //lint:file-ignore SA6001 Ignore all unused code, it's generated
End-to-End Tests

CI also runs end-to-end tests. These test the integration between the influx server the ui. You can run them locally in two steps:

  • Start the server in "testing mode" by running make run-e2e.
  • Run the tests with make e2e.

Documentation ¶

Index ¶

Constants ¶

View Source
const (
	OpFindAuthorizationByID    = "FindAuthorizationByID"
	OpFindAuthorizationByToken = "FindAuthorizationByToken"
	OpFindAuthorizations       = "FindAuthorizations"
	OpCreateAuthorization      = "CreateAuthorization"
	OpUpdateAuthorization      = "UpdateAuthorization"
	OpDeleteAuthorization      = "DeleteAuthorization"
)

auth service op

View Source
const (
	// AuthorizationsResourceType gives permissions to one or more authorizations.
	AuthorizationsResourceType = ResourceType("authorizations") // 0
	// BucketsResourceType gives permissions to one or more buckets.
	BucketsResourceType = ResourceType("buckets") // 1
	// DashboardsResourceType gives permissions to one or more dashboards.
	DashboardsResourceType = ResourceType("dashboards") // 2
	// OrgsResourceType gives permissions to one or more orgs.
	OrgsResourceType = ResourceType("orgs") // 3
	// SourcesResourceType gives permissions to one or more sources.
	SourcesResourceType = ResourceType("sources") // 4
	// TasksResourceType gives permissions to one or more tasks.
	TasksResourceType = ResourceType("tasks") // 5
	// TelegrafsResourceType type gives permissions to a one or more telegrafs.
	TelegrafsResourceType = ResourceType("telegrafs") // 6
	// UsersResourceType gives permissions to one or more users.
	UsersResourceType = ResourceType("users") // 7
	// VariablesResourceType gives permission to one or more variables.
	VariablesResourceType = ResourceType("variables") // 8
	// ScraperResourceType gives permission to one or more scrapers.
	ScraperResourceType = ResourceType("scrapers") // 9
	// SecretsResourceType gives permission to one or more secrets.
	SecretsResourceType = ResourceType("secrets") // 10
	// LabelsResourceType gives permission to one or more labels.
	LabelsResourceType = ResourceType("labels") // 11
	// ViewsResourceType gives permission to one or more views.
	ViewsResourceType = ResourceType("views") // 12
	// DocumentsResourceType gives permission to one or more documents.
	DocumentsResourceType = ResourceType("documents") // 13
	// NotificationRuleResourceType gives permission to one or more notificationRules.
	NotificationRuleResourceType = ResourceType("notificationRules") // 14
	// NotificationEndpointResourceType gives permission to one or more notificationEndpoints.
	NotificationEndpointResourceType = ResourceType("notificationEndpoints") // 15
	// ChecksResourceType gives permission to one or more Checks.
	ChecksResourceType = ResourceType("checks") // 16
	// DBRPType gives permission to one or more DBRPs.
	DBRPResourceType = ResourceType("dbrp") // 17
)
View Source
const (
	// BucketTypeUser is a user created bucket
	BucketTypeUser = BucketType(0)
	// BucketTypeSystem is an internally created bucket that cannot be deleted/renamed.
	BucketTypeSystem = BucketType(1)
	// MonitoringSystemBucketRetention is the time we should retain monitoring system bucket information
	MonitoringSystemBucketRetention = time.Hour * 24 * 7
	// TasksSystemBucketRetention is the time we should retain task system bucket information
	TasksSystemBucketRetention = time.Hour * 24 * 3
)
View Source
const (
	TasksSystemBucketName      = "_tasks"
	MonitoringSystemBucketName = "_monitoring"
)

Bucket names constants

View Source
const (
	CheckDefaultPageSize = 100
	CheckMaxPageSize     = 500
)

consts for checks config.

View Source
const (
	OpFindDashboardByID       = "FindDashboardByID"
	OpFindDashboards          = "FindDashboards"
	OpCreateDashboard         = "CreateDashboard"
	OpUpdateDashboard         = "UpdateDashboard"
	OpAddDashboardCell        = "AddDashboardCell"
	OpRemoveDashboardCell     = "RemoveDashboardCell"
	OpUpdateDashboardCell     = "UpdateDashboardCell"
	OpGetDashboardCellView    = "GetDashboardCellView"
	OpUpdateDashboardCellView = "UpdateDashboardCellView"
	OpDeleteDashboard         = "DeleteDashboard"
	OpReplaceDashboardCells   = "ReplaceDashboardCells"
)

ops for dashboard service.

View Source
const (
	ViewPropertyTypeCheck              = "check"
	ViewPropertyTypeGauge              = "gauge"
	ViewPropertyTypeHeatMap            = "heatmap"
	ViewPropertyTypeHistogram          = "histogram"
	ViewPropertyTypeLogViewer          = "log-viewer"
	ViewPropertyTypeMarkdown           = "markdown"
	ViewPropertyTypeScatter            = "scatter"
	ViewPropertyTypeSingleStat         = "single-stat"
	ViewPropertyTypeSingleStatPlusLine = "line-plus-single-stat"
	ViewPropertyTypeTable              = "table"
	ViewPropertyTypeXY                 = "xy"
	ViewPropertyTypeMosaic             = "mosaic"
	ViewPropertyTypeBand               = "band"
)

Values for all supported view property types.

View Source
const (
	EInternal            = "internal error"
	ENotImplemented      = "not implemented"
	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"
	ETooLarge            = "request too large"
)

Some error code constant, ideally we want define common platform codes here projects on use platform's error, should have their own central place like this. Any time this set of constants changes, you must also update the swagger for Error.properties.code.enum.

View Source
const (
	OpFindLabels         = "FindLabels"
	OpFindLabelByID      = "FindLabelByID"
	OpFindLabelMapping   = "FindLabelMapping"
	OpCreateLabel        = "CreateLabel"
	OpCreateLabelMapping = "CreateLabelMapping"
	OpUpdateLabel        = "UpdateLabel"
	OpDeleteLabel        = "DeleteLabel"
	OpDeleteLabelMapping = "DeleteLabelMapping"
)
View Source
const (
	OrgIDLength       = 8
	BucketIDLength    = 8
	MeasurementLength = OrgIDLength + BucketIDLength
)

Length of components of measurement names.

View Source
const (
	OpFindOrganizationByID = "FindOrganizationByID"
	OpFindOrganization     = "FindOrganization"
	OpFindOrganizations    = "FindOrganizations"
	OpCreateOrganization   = "CreateOrganization"
	OpPutOrganization      = "PutOrganization"
	OpUpdateOrganization   = "UpdateOrganization"
	OpDeleteOrganization   = "DeleteOrganization"
)

ops for orgs error and orgs op logs.

View Source
const (
	DefaultPageSize = 20
	MaxPageSize     = 100
)
View Source
const (
	OpListTargets   = "ListTargets"
	OpAddTarget     = "AddTarget"
	OpGetTargetByID = "GetTargetByID"
	OpRemoveTarget  = "RemoveTarget"
	OpUpdateTarget  = "UpdateTarget"
)

ops for ScraperTarget Store

View Source
const (
	// V2SourceType is an InfluxDBv2 type.
	V2SourceType = "v2"
	// V1SourceType is an InfluxDBv1 type.
	V1SourceType = "v1"
	// SelfSourceType is the source hosting the UI.
	SelfSourceType = "self"
)
View Source
const (
	OpDefaultSource  = "DefaultSource"
	OpFindSourceByID = "FindSourceByID"
	OpFindSources    = "FindSources"
	OpCreateSource   = "CreateSource"
	OpUpdateSource   = "UpdateSource"
	OpDeleteSource   = "DeleteSource"
)

ops for sources.

View Source
const (
	TaskDefaultPageSize = 100
	TaskMaxPageSize     = 500

	TaskStatusActive   = "active"
	TaskStatusInactive = "inactive"
)
View Source
const (
	ErrTelegrafConfigInvalidOrgID  = "invalid org ID"                   // ErrTelegrafConfigInvalidOrgID is the error message for a missing or invalid organization ID.
	ErrTelegrafConfigNotFound      = "telegraf configuration not found" // ErrTelegrafConfigNotFound is the error message for a missing telegraf config.
	ErrTelegrafPluginNameUnmatch   = "the telegraf plugin is name %s doesn't match the config %s"
	ErrNoTelegrafPlugins           = "there is no telegraf plugin in the config"
	ErrUnsupportTelegrafPluginType = "unsupported telegraf plugin type %s"
	ErrUnsupportTelegrafPluginName = "unsupported telegraf plugin %s, type %s"
)
View Source
const (
	OpFindUserByID = "FindUserByID"
	OpFindUser     = "FindUser"
	OpFindUsers    = "FindUsers"
	OpCreateUser   = "CreateUser"
	OpUpdateUser   = "UpdateUser"
	OpDeleteUser   = "DeleteUser"
)

Ops for user errors and op log.

View Source
const (
	UserMappingType = 0
	OrgMappingType  = 1
)
View Source
const (
	OpFindVariableByID = "FindVariableByID"
	OpFindVariables    = "FindVariables"
	OpCreateVariable   = "CreateVariable"
	OpUpdateVariable   = "UpdateVariable"
	OpReplaceVariable  = "ReplaceVariable"
	OpDeleteVariable   = "DeleteVariable"
)

ops for variable error.

View Source
const AuthorizationKind = "authorization"

AuthorizationKind is returned by (*Authorization).Kind().

View Source
const (
	BackupFilenamePattern = "20060102T150405Z"
)
View Source
const DefaultLeaseTTL = time.Minute

DefaultLeaseTTL is used when a specific lease TTL is not requested.

View Source
const ErrCellNotFound = "cell not found"

ErrCellNotFound is the error msg for a missing cell.

View Source
const ErrDashboardNotFound = "dashboard not found"

ErrDashboardNotFound is the error msg for a missing dashboard.

View Source
const ErrDocumentNotFound = "document not found"

ErrDocumentNotFound is the error msg for a missing document.

View Source
const ErrLabelNotFound = "label not found"

ErrLabelNotFound is the error for a missing Label.

View Source
const ErrScraperTargetNotFound = "scraper target not found"

ErrScraperTargetNotFound is the error msg for a missing scraper target.

View Source
const ErrSecretNotFound = "secret not found"

ErrSecretNotFound is the error msg for a missing secret.

View Source
const ErrSessionExpired = "session has expired"

ErrSessionExpired is the error message for expired sessions.

View Source
const ErrSessionNotFound = "session not found"

ErrSessionNotFound is the error messages for a missing sessions.

View Source
const (
	// ErrSourceNotFound is an error message when a source does not exist.
	ErrSourceNotFound = "source not found"
)
View Source
const ErrVariableNotFound = "variable not found"

ErrVariableNotFound is the error msg for a missing variable.

View Source
const ErrViewNotFound = "view not found"

ErrViewNotFound is the error msg for a missing View.

View Source
const IDLength = 16

IDLength is the exact length a string (or a byte slice representing it) must have in order to be decoded into a valid ID.

View Source
const InfiniteRetention = 0

InfiniteRetention is default infinite retention period.

View Source
const (
	// PrometheusScraperType parses metrics from a prometheus endpoint.
	PrometheusScraperType = "prometheus"
)

Scraper types

View Source
const SessionAuthorizationKind = "session"

SessionAuthorizationKind defines the type of authorizer

Variables ¶

View Source
var (
	// ErrAuthorizerNotSupported notes that the provided authorizer is not supported for the action you are trying to perform.
	ErrAuthorizerNotSupported = errors.New("your authorizer is not supported, please use *platform.Authorization as authorizer")
	// ErrInvalidResourceType notes that the provided resource is invalid
	ErrInvalidResourceType = errors.New("unknown resource type for permission")
	// ErrInvalidAction notes that the provided action is invalid
	ErrInvalidAction = errors.New("unknown action for permission")
)
View Source
var (
	OpFindBucketByID = "FindBucketByID"
	OpFindBucket     = "FindBucket"
	OpFindBuckets    = "FindBuckets"
	OpCreateBucket   = "CreateBucket"
	OpPutBucket      = "PutBucket"
	OpUpdateBucket   = "UpdateBucket"
	OpDeleteBucket   = "DeleteBucket"
)

ops for buckets error and buckets op logs.

View Source
var (
	OpFindCheckByID = "FindCheckByID"
	OpFindCheck     = "FindCheck"
	OpFindChecks    = "FindChecks"
	OpCreateCheck   = "CreateCheck"
	OpUpdateCheck   = "UpdateCheck"
	OpDeleteCheck   = "DeleteCheck"
)

ops for checks error

View Source
var (
	// ErrInvalidID signifies invalid IDs.
	ErrInvalidID = &Error{
		Code: EInvalid,
		Msg:  "invalid ID",
	}

	// ErrInvalidIDLength is returned when an ID has the incorrect number of bytes.
	ErrInvalidIDLength = &Error{
		Code: EInvalid,
		Msg:  "id must have a length of 16 bytes",
	}
)
View Source
var (
	// ErrLabelNameisEmpty is error when org name is empty
	ErrLabelNameisEmpty = &Error{
		Code: EInvalid,
		Msg:  "label name is empty",
	}

	// ErrLabelExistsOnResource is used when attempting to add a label to a resource
	// when that label already exists on the resource
	ErrLabelExistsOnResource = &Error{
		Code: EConflict,
		Msg:  "Cannot add label, label already exists on resource",
	}
)

errors on label

View Source
var (
	OpFindNotificationEndpointByID = "FindNotificationEndpointByID"
	OpFindNotificationEndpoint     = "FindNotificationEndpoint"
	OpFindNotificationEndpoints    = "FindNotificationEndpoints"
	OpCreateNotificationEndpoint   = "CreateNotificationEndpoint"
	OpUpdateNotificationEndpoint   = "UpdateNotificationEndpoint"
	OpDeleteNotificationEndpoint   = "DeleteNotificationEndpoint"
)

ops for checks error

View Source
var (
	// OpFindSession represents the operation that looks for sessions.
	OpFindSession = "FindSession"
	// OpExpireSession represents the operation that expires sessions.
	OpExpireSession = "ExpireSession"
	// OpCreateSession represents the operation that creates a session for a given user.
	OpCreateSession = "CreateSession"
	// OpRenewSession = "RenewSession"
	OpRenewSession = "RenewSession"
)
View Source
var (
	// ErrRunCanceled is returned from the RunResult when a Run is Canceled.  It is used mostly internally.
	ErrRunCanceled = &Error{
		Code: EInternal,
		Msg:  "run canceled",
	}

	// ErrTaskNotClaimed is returned when attempting to operate against a task that must be claimed but is not.
	ErrTaskNotClaimed = &Error{
		Code: EConflict,
		Msg:  "task not claimed",
	}

	// ErrTaskAlreadyClaimed is returned when attempting to operate against a task that must not be claimed but is.
	ErrTaskAlreadyClaimed = &Error{
		Code: EConflict,
		Msg:  "task already claimed",
	}

	// ErrNoRunsFound is returned when searching for a range of runs, but none are found.
	ErrNoRunsFound = &Error{
		Code: ENotFound,
		Msg:  "no matching runs found",
	}

	// ErrInvalidTaskID error object for bad id's
	ErrInvalidTaskID = &Error{
		Code: EInvalid,
		Msg:  "invalid id",
	}

	// ErrTaskNotFound indicates no task could be found for given parameters.
	ErrTaskNotFound = &Error{
		Code: ENotFound,
		Msg:  "task not found",
	}

	// ErrRunNotFound is returned when searching for a single run that doesn't exist.
	ErrRunNotFound = &Error{
		Code: ENotFound,
		Msg:  "run not found",
	}

	ErrRunKeyNotFound = &Error{
		Code: ENotFound,
		Msg:  "run key not found",
	}

	ErrPageSizeTooSmall = &Error{
		Msg:  "cannot have negative page limit",
		Code: EInvalid,
	}

	// ErrPageSizeTooLarge indicates the page size is too large. This error is only
	// used in the kv task service implementation. The name of this error may lead it
	// to be used in a place that is not useful. The TaskMaxPageSize is the only one
	// at 500, the rest at 100. This would likely benefit from a more specific name
	// since those limits aren't shared globally.
	ErrPageSizeTooLarge = &Error{
		Msg:  fmt.Sprintf("cannot use page size larger then %d", TaskMaxPageSize),
		Code: EInvalid,
	}

	ErrOrgNotFound = &Error{
		Msg:  "organization not found",
		Code: ENotFound,
	}

	ErrTaskRunAlreadyQueued = &Error{
		Msg:  "run already queued",
		Code: EConflict,
	}

	// ErrOutOfBoundsLimit is returned with FindRuns is called with an invalid filter limit.
	ErrOutOfBoundsLimit = &Error{
		Code: EUnprocessableEntity,
		Msg:  "run limit is out of bounds, must be between 1 and 500",
	}

	// ErrInvalidOwnerID is called when trying to create a task with out a valid ownerID
	ErrInvalidOwnerID = &Error{
		Code: EInvalid,
		Msg:  "cannot create task with invalid ownerID",
	}
)
View Source
var (
	OpFindTelegrafConfigByID = "FindTelegrafConfigByID"
	OpFindTelegrafConfigs    = "FindTelegrafConfigs"
	OpCreateTelegrafConfig   = "CreateTelegrafConfig"
	OpUpdateTelegrafConfig   = "UpdateTelegrafConfig"
	OpDeleteTelegrafConfig   = "DeleteTelegrafConfig"
)

ops for buckets error and buckets op logs.

View Source
var (
	// ErrInvalidUserType notes that the provided UserType is invalid
	ErrInvalidUserType = errors.New("unknown user type")
	// ErrInvalidMappingType notes that the provided MappingType is invalid
	ErrInvalidMappingType = errors.New("unknown mapping type")
	// ErrUserIDRequired notes that the ID was not provided
	ErrUserIDRequired = errors.New("user id is required")
	// ErrResourceIDRequired notes that the provided ID was not provided
	ErrResourceIDRequired = errors.New("resource id is required")
)

AllResourceTypes is the list of all known resource types.

View Source
var DefaultDashboardFindOptions = FindOptions{
	SortBy: "ID",
}

DefaultDashboardFindOptions are the default find options for dashboards

View Source
var DefaultOperationLogFindOptions = FindOptions{
	Descending: true,
	Limit:      100,
}

DefaultOperationLogFindOptions are the default options for the operation log.

View Source
var DefaultSessionLength = time.Hour

DefaultSessionLength is the default session length on initial creation.

View Source
var DefaultSourceFindOptions = FindOptions{}

DefaultSourceFindOptions are the default find options for sources

View Source
var DefaultVariableFindOptions = FindOptions{}

DefaultVariableFindOptions are the default find options for variables.

View Source
var (
	// ErrCredentialsUnauthorized is the error returned when CredentialsV1 cannot be
	// authorized.
	ErrCredentialsUnauthorized = &Error{
		Code: EUnauthorized,
		Msg:  "Unauthorized",
	}
)
View Source
var (
	// ErrInvalidNotificationEndpointType denotes that the provided NotificationEndpoint is not a valid type
	ErrInvalidNotificationEndpointType = errors.New("unknown notification endpoint type")
)
View Source
var ErrInvalidOrgFilter = &Error{
	Code: EInvalid,
	Msg:  "Please provide either orgID or org",
}

ErrInvalidOrgFilter is the error indicate org filter is empty

View Source
var ErrNoAcquire = errors.New("ownership not acquired")

ErrNoAcquire is returned when it was not possible to acquire ownership of the semaphore.

View Source
var (
	// ErrOrgNameisEmpty is error when org name is empty
	ErrOrgNameisEmpty = &Error{
		Code: EInvalid,
		Msg:  "org name is empty",
	}
)

errors of org

View Source
var ErrUnableToCreateToken = &Error{
	Msg:  "unable to create token",
	Code: EInvalid,
}

ErrUnableToCreateToken sanitized error message for all errors when a user cannot create a token

OrgResourceTypes is the list of all known resource types that belong to an organization.

View Source
var RenewSessionTime = time.Duration(time.Second * 300)

RenewSessionTime is the the time to extend session, currently set to 5min.

View Source
var (
	// TaskSystemType is the type set in tasks' for all crud requests
	TaskSystemType = "system"
)

Functions ¶

func CreateMeasurement ¶

func CreateMeasurement(org, bucket []byte) ([]byte, error)

CreateMeasurement returns 16 bytes that represent a measurement.

If either org or bucket are short then an error is returned, otherwise the first 8 bytes of each are combined and returned.

func ErrorCode ¶

func ErrorCode(err error) string

ErrorCode returns the code of the root error, if available; otherwise returns EINTERNAL.

func ErrorMessage ¶

func ErrorMessage(err error) string

ErrorMessage returns the human-readable message of the error, if available. Otherwise returns a generic error message.

func ErrorOp ¶

func ErrorOp(err error) string

ErrorOp returns the op of the error, if available; otherwise return empty string.

func FindOptionParams ¶

func FindOptionParams(opts ...FindOptions) [][2]string

func IsActive ¶

func IsActive(a *Authorization) bool

IsActive is a stub for idpe.

func MarshalViewPropertiesJSON ¶

func MarshalViewPropertiesJSON(v ViewProperties) ([]byte, error)

MarshalViewPropertiesJSON encodes a view into JSON bytes.

func NewBuilderTag ¶

func NewBuilderTag(key string, functionType string, values ...string) struct {
	Key                   string   `json:"key"`
	Values                []string `json:"values"`
	AggregateFunctionType string   `json:"aggregateFunctionType"`
}

NewBuilderTag is a constructor for the builder config types. This isn't technically required, but working with struct literals with embedded struct tags is really painful. This is to get around that bit. Would be nicer to have these as actual types maybe.

func PermissionAllowed ¶

func PermissionAllowed(perm Permission, ps []Permission) bool

PermissionAllowed determines if a permission is allowed.

func ReadMeasurement ¶

func ReadMeasurement(name []byte) (orgID, bucketID []byte, err error)

ReadMeasurement reads the provided measurement name and returns an Org ID and bucket ID. It returns an error if the provided name has an invalid length.

ReadMeasurement does not allocate, and instead returns sub-slices of name, so callers should be careful about subsequent mutations to the provided name slice.

func SetBuildInfo ¶

func SetBuildInfo(version, commit, date string)

SetBuildInfo sets the build information for the binary.

func SortDashboards ¶

func SortDashboards(opts FindOptions, ds []*Dashboard)

SortDashboards sorts a slice of dashboards by a field.

func ValidScraperType ¶

func ValidScraperType(s string) bool

ValidScraperType returns true is the type string is valid

func WithErrorCode ¶

func WithErrorCode(code string) func(*Error)

WithErrorCode sets the code on the error.

func WithErrorErr ¶

func WithErrorErr(err error) func(*Error)

WithErrorErr sets the err on the error.

func WithErrorMsg ¶

func WithErrorMsg(msg string) func(*Error)

WithErrorMsg sets the message on the error.

func WithErrorOp ¶

func WithErrorOp(op string) func(*Error)

WithErrorOp sets the message on the error.

Types ¶

type Action ¶

type Action string

Action is an enum defining all possible resource operations

const (
	// ReadAction is the action for reading.
	ReadAction Action = "read" // 1
	// WriteAction is the action for writing.
	WriteAction Action = "write" // 2
)

func (Action) Valid ¶

func (a Action) Valid() (err error)

Valid checks if the action is a member of the Action enum

type AddDashboardCellOptions ¶

type AddDashboardCellOptions struct {
	View *View
}

AddDashboardCellOptions are options for adding a dashboard.

type Authorization ¶

type Authorization struct {
	ID          ID           `json:"id"`
	Token       string       `json:"token"`
	Status      Status       `json:"status"`
	Description string       `json:"description"`
	OrgID       ID           `json:"orgID"`
	UserID      ID           `json:"userID,omitempty"`
	Permissions []Permission `json:"permissions"`
	CRUDLog
}

Authorization is an authorization. 🎉

func (*Authorization) GetUserID ¶

func (a *Authorization) GetUserID() ID

GetUserID returns the user id.

func (*Authorization) Identifier ¶

func (a *Authorization) Identifier() ID

Identifier returns the authorizations ID and is used for auditing.

func (*Authorization) IsActive ¶

func (a *Authorization) IsActive() bool

IsActive returns true if the authorization active.

func (*Authorization) Kind ¶

func (a *Authorization) Kind() string

Kind returns session and is used for auditing.

func (*Authorization) PermissionSet ¶

func (a *Authorization) PermissionSet() (PermissionSet, error)

PermissionSet returns the set of permissions associated with the Authorization.

func (*Authorization) Valid ¶

func (a *Authorization) Valid() error

Valid ensures that the authorization is valid.

type AuthorizationFilter ¶

type AuthorizationFilter struct {
	Token *string
	ID    *ID

	UserID *ID
	User   *string

	OrgID *ID
	Org   *string
}

AuthorizationFilter represents a set of filter that restrict the returned results.

type AuthorizationService ¶

type AuthorizationService interface {
	// Returns a single authorization by ID.
	FindAuthorizationByID(ctx context.Context, id ID) (*Authorization, error)

	// Returns a single authorization by Token.
	FindAuthorizationByToken(ctx context.Context, t string) (*Authorization, error)

	// Returns a list of authorizations that match filter and the total count of matching authorizations.
	// Additional options provide pagination & sorting.
	FindAuthorizations(ctx context.Context, filter AuthorizationFilter, opt ...FindOptions) ([]*Authorization, int, error)

	// Creates a new authorization and sets a.Token and a.UserID with the new identifier.
	CreateAuthorization(ctx context.Context, a *Authorization) error

	// UpdateAuthorization updates the status and description if available.
	UpdateAuthorization(ctx context.Context, id ID, upd *AuthorizationUpdate) (*Authorization, error)

	// Removes a authorization by token.
	DeleteAuthorization(ctx context.Context, id ID) error
}

AuthorizationService represents a service for managing authorization data.

type AuthorizationUpdate ¶

type AuthorizationUpdate struct {
	Status      *Status `json:"status,omitempty"`
	Description *string `json:"description,omitempty"`
}

AuthorizationUpdate is the authorization update request.

type Authorizer ¶

type Authorizer interface {
	// PermissionSet returns the PermissionSet associated with the authorizer
	PermissionSet() (PermissionSet, error)

	// ID returns an identifier used for auditing.
	Identifier() ID

	// GetUserID returns the user id.
	GetUserID() ID

	// Kind metadata for auditing.
	Kind() string
}

Authorizer will authorize a permission.

type AuthorizerV1 ¶

type AuthorizerV1 interface {
	Authorize(ctx context.Context, v1 CredentialsV1) (*Authorization, error)
}

type Axis ¶

type Axis struct {
	Bounds       []string `json:"bounds"` // bounds are an arbitrary list of client-defined strings that specify the viewport for a View
	LegacyBounds [2]int64 `json:"-"`      // legacy bounds are for testing a migration from an earlier version of axis
	Label        string   `json:"label"`  // label is a description of this Axis
	Prefix       string   `json:"prefix"` // Prefix represents a label prefix for formatting axis values
	Suffix       string   `json:"suffix"` // Suffix represents a label suffix for formatting axis values
	Base         string   `json:"base"`   // Base represents the radix for formatting axis values
	Scale        string   `json:"scale"`  // Scale is the axis formatting scale. Supported: "log", "linear"
}

Axis represents the visible extents of a visualization

type BackupService ¶

type BackupService interface {
	// BackupKVStore creates a live backup copy of the metadata database.
	BackupKVStore(ctx context.Context, w io.Writer) error

	// BackupShard downloads a backup file for a single shard.
	BackupShard(ctx context.Context, w io.Writer, shardID uint64, since time.Time) error
}

BackupService represents the data backup functions of InfluxDB.

type BandViewProperties ¶

type BandViewProperties struct {
	Queries                    []DashboardQuery `json:"queries"`
	Axes                       map[string]Axis  `json:"axes"`
	Type                       string           `json:"type"`
	Legend                     Legend           `json:"legend"`
	Geom                       string           `json:"geom"`
	ViewColors                 []ViewColor      `json:"colors"`
	Note                       string           `json:"note"`
	ShowNoteWhenEmpty          bool             `json:"showNoteWhenEmpty"`
	TimeFormat                 string           `json:"timeFormat"`
	HoverDimension             string           `json:"hoverDimension"`
	XColumn                    string           `json:"xColumn"`
	GenerateXAxisTicks         []string         `json:"generateXAxisTicks"`
	XTotalTicks                int              `json:"xTotalTicks"`
	XTickStart                 float64          `json:"xTickStart"`
	XTickStep                  float64          `json:"xTickStep"`
	YColumn                    string           `json:"yColumn"`
	GenerateYAxisTicks         []string         `json:"generateYAxisTicks"`
	YTotalTicks                int              `json:"yTotalTicks"`
	YTickStart                 float64          `json:"yTickStart"`
	YTickStep                  float64          `json:"yTickStep"`
	UpperColumn                string           `json:"upperColumn"`
	MainColumn                 string           `json:"mainColumn"`
	LowerColumn                string           `json:"lowerColumn"`
	LegendColorizeRows         bool             `json:"legendColorizeRows"`
	LegendOpacity              float64          `json:"legendOpacity"`
	LegendOrientationThreshold int              `json:"legendOrientationThreshold"`
}

BandViewProperties represents options for the band view

func (BandViewProperties) GetType ¶

func (v BandViewProperties) GetType() string

type Bucket ¶

type Bucket struct {
	ID                  ID            `json:"id,omitempty"`
	OrgID               ID            `json:"orgID,omitempty"`
	Type                BucketType    `json:"type"`
	Name                string        `json:"name"`
	Description         string        `json:"description"`
	RetentionPolicyName string        `json:"rp,omitempty"` // This to support v1 sources
	RetentionPeriod     time.Duration `json:"retentionPeriod"`
	ShardGroupDuration  time.Duration `json:"shardGroupDuration"`
	CRUDLog
}

Bucket is a bucket. 🎉

func (*Bucket) Clone ¶

func (b *Bucket) Clone() *Bucket

Clone returns a shallow copy of b.

type BucketFilter ¶

type BucketFilter struct {
	ID             *ID
	Name           *string
	OrganizationID *ID
	Org            *string
}

BucketFilter represents a set of filter that restrict the returned results.

func (BucketFilter) QueryParams ¶

func (f BucketFilter) QueryParams() map[string][]string

QueryParams Converts BucketFilter fields to url query params.

func (BucketFilter) String ¶

func (f BucketFilter) String() string

String returns a human-readable string of the BucketFilter, particularly useful for error messages.

type BucketOperationLogService ¶

type BucketOperationLogService interface {
	// GetBucketOperationLog retrieves the operation log for the bucket with the provided id.
	GetBucketOperationLog(ctx context.Context, id ID, opts FindOptions) ([]*OperationLogEntry, int, error)
}

BucketOperationLogService is an interface for retrieving the operation log for a bucket.

type BucketService ¶

type BucketService interface {
	// FindBucketByID returns a single bucket by ID.
	FindBucketByID(ctx context.Context, id ID) (*Bucket, error)

	// FindBucket returns the first bucket that matches filter.
	FindBucket(ctx context.Context, filter BucketFilter) (*Bucket, error)

	// FindBuckets returns a list of buckets that match filter and the total count of matching buckets.
	// Additional options provide pagination & sorting.
	FindBuckets(ctx context.Context, filter BucketFilter, opt ...FindOptions) ([]*Bucket, int, error)

	// CreateBucket creates a new bucket and sets b.ID with the new identifier.
	CreateBucket(ctx context.Context, b *Bucket) error

	// UpdateBucket updates a single bucket with changeset.
	// Returns the new bucket state after update.
	UpdateBucket(ctx context.Context, id ID, upd BucketUpdate) (*Bucket, error)

	// DeleteBucket removes a bucket by ID.
	DeleteBucket(ctx context.Context, id ID) error
	FindBucketByName(ctx context.Context, orgID ID, name string) (*Bucket, error)
}

BucketService represents a service for managing bucket data.

type BucketType ¶

type BucketType int

BucketType differentiates system buckets from user buckets.

func ParseBucketType ¶

func ParseBucketType(s string) BucketType

ParseBucketType parses a bucket type from a string

func (BucketType) String ¶

func (bt BucketType) String() string

String converts a BucketType into a human-readable string.

type BucketUpdate ¶

type BucketUpdate struct {
	Name               *string
	Description        *string
	RetentionPeriod    *time.Duration
	ShardGroupDuration *time.Duration
}

BucketUpdate represents updates to a bucket. Only fields which are set are updated.

type BuildInfo ¶

type BuildInfo struct {
	Version string // Version is the current git tag with v prefix stripped
	Commit  string // Commit is the current git commit SHA
	Date    string // Date is the build date in RFC3339
}

BuildInfo represents the information about InfluxDB build.

func GetBuildInfo ¶

func GetBuildInfo() BuildInfo

GetBuildInfo returns the current build information for the binary.

type BuilderConfig ¶

type BuilderConfig struct {
	Buckets []string `json:"buckets"`
	Tags    []struct {
		Key                   string   `json:"key"`
		Values                []string `json:"values"`
		AggregateFunctionType string   `json:"aggregateFunctionType"`
	} `json:"tags"`
	Functions []struct {
		Name string `json:"name"`
	} `json:"functions"`
	AggregateWindow struct {
		Period     string `json:"period"`
		FillValues bool   `json:"fillValues"`
	} `json:"aggregateWindow"`
}

func (BuilderConfig) MarshalJSON ¶

func (b BuilderConfig) MarshalJSON() ([]byte, error)

MarshalJSON is necessary for the time being. UI keeps breaking b/c it relies on these slices being populated/not nil. Other consumers may have same issue.

type CRUDLog ¶

type CRUDLog struct {
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
}

CRUDLog is the struct to store crud related ops.

func (*CRUDLog) SetCreatedAt ¶

func (log *CRUDLog) SetCreatedAt(now time.Time)

SetCreatedAt set the created time.

func (*CRUDLog) SetUpdatedAt ¶

func (log *CRUDLog) SetUpdatedAt(now time.Time)

SetUpdatedAt set the updated time.

type CRUDLogSetter ¶

type CRUDLogSetter interface {
	SetCreatedAt(now time.Time)
	SetUpdatedAt(now time.Time)
}

CRUDLogSetter is the interface to set the crudlog.

type Cell ¶

type Cell struct {
	ID ID `json:"id,omitempty"`
	CellProperty
	View *View `json:"-"`
}

Cell holds positional information about a cell on dashboard and a reference to a cell.

func (*Cell) MarshalJSON ¶

func (c *Cell) MarshalJSON() ([]byte, error)

Marshals the cell

func (*Cell) UnmarshalJSON ¶

func (c *Cell) UnmarshalJSON(b []byte) error

type CellProperty ¶

type CellProperty struct {
	X int32 `json:"x"`
	Y int32 `json:"y"`
	W int32 `json:"w"`
	H int32 `json:"h"`
}

CellProperty contains the properties of a cell.

type CellUpdate ¶

type CellUpdate struct {
	X *int32 `json:"x"`
	Y *int32 `json:"y"`
	W *int32 `json:"w"`
	H *int32 `json:"h"`
}

CellUpdate is the patch structure for a cell.

func (CellUpdate) Apply ¶

func (u CellUpdate) Apply(c *Cell) error

Apply applies an update to a Cell.

func (CellUpdate) Valid ¶

func (u CellUpdate) Valid() *Error

Valid returns an error if the cell update is invalid.

type Check ¶

type Check interface {
	Valid(lang FluxLanguageService) error
	Type() string
	ClearPrivateData()
	SetTaskID(ID)
	GetTaskID() ID
	GetOwnerID() ID
	SetOwnerID(ID)
	GenerateFlux(lang FluxLanguageService) (string, error)
	json.Marshaler

	CRUDLogSetter
	SetID(id ID)
	SetOrgID(id ID)
	SetName(name string)
	SetDescription(description string)

	GetID() ID
	GetCRUDLog() CRUDLog
	GetOrgID() ID
	GetName() string
	GetDescription() string
}

Check represents the information required to generate a periodic check task.

type CheckCreate ¶

type CheckCreate struct {
	Check
	Status Status `json:"status"`
}

CheckCreate represent data to create a new Check

type CheckFilter ¶

type CheckFilter struct {
	ID    *ID
	Name  *string
	OrgID *ID
	Org   *string
	UserResourceMappingFilter
}

CheckFilter represents a set of filters that restrict the returned results.

func (CheckFilter) QueryParams ¶

func (f CheckFilter) QueryParams() map[string][]string

QueryParams Converts CheckFilter fields to url query params.

type CheckService ¶

type CheckService interface {
	// FindCheckByID returns a single check by ID.
	FindCheckByID(ctx context.Context, id ID) (Check, error)

	// FindCheck returns the first check that matches filter.
	FindCheck(ctx context.Context, filter CheckFilter) (Check, error)

	// FindChecks returns a list of checks that match filter and the total count of matching checks.
	// Additional options provide pagination & sorting.
	FindChecks(ctx context.Context, filter CheckFilter, opt ...FindOptions) ([]Check, int, error)

	// CreateCheck creates a new check and sets b.ID with the new identifier.
	CreateCheck(ctx context.Context, c CheckCreate, userID ID) error

	// UpdateCheck updates the whole check.
	// Returns the new check state after update.
	UpdateCheck(ctx context.Context, id ID, c CheckCreate) (Check, error)

	// PatchCheck updates a single bucket with changeset.
	// Returns the new check state after update.
	PatchCheck(ctx context.Context, id ID, upd CheckUpdate) (Check, error)

	// DeleteCheck will delete the check by id.
	DeleteCheck(ctx context.Context, id ID) error
}

CheckService represents a service for managing checks.

type CheckUpdate ¶

type CheckUpdate struct {
	Name        *string `json:"name,omitempty"`
	Status      *Status `json:"status,omitempty"`
	Description *string `json:"description,omitempty"`
}

CheckUpdate are properties than can be updated on a check

func (*CheckUpdate) Valid ¶

func (n *CheckUpdate) Valid() error

Valid returns err is the update is invalid.

type CheckViewProperties ¶

type CheckViewProperties struct {
	Type                       string           `json:"type"`
	CheckID                    string           `json:"checkID"`
	Queries                    []DashboardQuery `json:"queries"`
	ViewColors                 []string         `json:"colors"`
	LegendColorizeRows         bool             `json:"legendColorizeRows"`
	LegendOpacity              float64          `json:"legendOpacity"`
	LegendOrientationThreshold int              `json:"legendOrientationThreshold"`
}

CheckViewProperties represents options for a view representing a check

func (CheckViewProperties) GetType ¶

func (v CheckViewProperties) GetType() string

type CredentialsV1 ¶

type CredentialsV1 struct {
	Scheme   SchemeV1
	Username string
	Token    string
}

CredentialsV1 encapsulates the required credentials to authorize a v1 HTTP request.

type DBRPMapping ¶

type DBRPMapping struct {
	Cluster         string `json:"cluster"`
	Database        string `json:"database"`
	RetentionPolicy string `json:"retention_policy"`

	// Default indicates if this mapping is the default for the cluster and database.
	Default bool `json:"default"`

	OrganizationID ID `json:"organization_id"`
	BucketID       ID `json:"bucket_id"`
}

DBRPMapping represents a mapping of a cluster, database and retention policy to an organization ID and bucket ID.

func (*DBRPMapping) Equal ¶

func (m *DBRPMapping) Equal(o *DBRPMapping) bool

Equal checks if the two mappings are identical.

func (DBRPMapping) Validate ¶

func (m DBRPMapping) Validate() error

Validate reports any validation errors for the mapping.

type DBRPMappingFilter ¶

type DBRPMappingFilter struct {
	Cluster         *string
	Database        *string
	RetentionPolicy *string
	Default         *bool
}

DBRPMappingFilter represents a set of filters that restrict the returned results by cluster, database and retention policy.

func (DBRPMappingFilter) String ¶

func (f DBRPMappingFilter) String() string

type DBRPMappingFilterV2 ¶

type DBRPMappingFilterV2 struct {
	ID       *ID
	OrgID    *ID
	BucketID *ID

	Database        *string
	RetentionPolicy *string
	Default         *bool
}

DBRPMappingFilterV2 represents a set of filters that restrict the returned results.

func (DBRPMappingFilterV2) String ¶

func (f DBRPMappingFilterV2) String() string

type DBRPMappingService ¶

type DBRPMappingService interface {
	// FindBy returns the dbrp mapping the for cluster, db and rp.
	FindBy(ctx context.Context, cluster, db, rp string) (*DBRPMapping, error)
	// Find returns the first dbrp mapping the matches the filter.
	Find(ctx context.Context, filter DBRPMappingFilter) (*DBRPMapping, error)
	// FindMany returns a list of dbrp mappings that match filter and the total count of matching dbrp mappings.
	FindMany(ctx context.Context, filter DBRPMappingFilter, opt ...FindOptions) ([]*DBRPMapping, int, error)
	// Create creates a new dbrp mapping, if a different mapping exists an error is returned.
	Create(ctx context.Context, dbrpMap *DBRPMapping) error
	// Delete removes a dbrp mapping.
	// Deleting a mapping that does not exists is not an error.
	Delete(ctx context.Context, cluster, db, rp string) error
}

DBRPMappingService provides a mapping of cluster, database and retention policy to an organization ID and bucket ID.

type DBRPMappingServiceV2 ¶

type DBRPMappingServiceV2 interface {
	// FindBy returns the dbrp mapping for the specified ID.
	// Requires orgID because every resource will be org-scoped.
	FindByID(ctx context.Context, orgID, id ID) (*DBRPMappingV2, error)
	// FindMany returns a list of dbrp mappings that match filter and the total count of matching dbrp mappings.
	FindMany(ctx context.Context, dbrp DBRPMappingFilterV2, opts ...FindOptions) ([]*DBRPMappingV2, int, error)
	// Create creates a new dbrp mapping, if a different mapping exists an error is returned.
	Create(ctx context.Context, dbrp *DBRPMappingV2) error
	// Update a new dbrp mapping
	Update(ctx context.Context, dbrp *DBRPMappingV2) error
	// Delete removes a dbrp mapping.
	// Deleting a mapping that does not exists is not an error.
	// Requires orgID because every resource will be org-scoped.
	Delete(ctx context.Context, orgID, id ID) error
}

DBRPMappingServiceV2 provides CRUD to DBRPMappingV2s.

type DBRPMappingV2 ¶

type DBRPMappingV2 struct {
	ID              ID     `json:"id"`
	Database        string `json:"database"`
	RetentionPolicy string `json:"retention_policy"`

	// Default indicates if this mapping is the default for the cluster and database.
	Default bool `json:"default"`

	OrganizationID ID `json:"orgID"`
	BucketID       ID `json:"bucketID"`
}

DBRPMappingV2 represents a mapping of a database and retention policy to an organization ID and bucket ID.

func (*DBRPMappingV2) Equal ¶

func (m *DBRPMappingV2) Equal(o *DBRPMappingV2) bool

Equal checks if the two mappings are identical.

func (DBRPMappingV2) Validate ¶

func (m DBRPMappingV2) Validate() error

Validate reports any validation errors for the mapping.

type Dashboard ¶

type Dashboard struct {
	ID             ID            `json:"id,omitempty"`
	OrganizationID ID            `json:"orgID,omitempty"`
	Name           string        `json:"name"`
	Description    string        `json:"description"`
	Cells          []*Cell       `json:"cells"`
	Meta           DashboardMeta `json:"meta"`
	OwnerID        *ID           `json:"owner,omitempty"`
}

Dashboard represents all visual and query data for a dashboard.

type DashboardFilter ¶

type DashboardFilter struct {
	IDs            []*ID
	OrganizationID *ID
	Organization   *string
	OwnerID        *ID
}

DashboardFilter is a filter for dashboards.

func (DashboardFilter) QueryParams ¶

func (f DashboardFilter) QueryParams() map[string][]string

QueryParams turns a dashboard filter into query params

It implements PagingFilter.

type DashboardMeta ¶

type DashboardMeta struct {
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
}

DashboardMeta contains meta information about dashboards

type DashboardOperationLogService ¶

type DashboardOperationLogService interface {
	// GetDashboardOperationLog retrieves the operation log for the dashboard with the provided id.
	GetDashboardOperationLog(ctx context.Context, id ID, opts FindOptions) ([]*OperationLogEntry, int, error)
}

DashboardOperationLogService is an interface for retrieving the operation log for a dashboard.

type DashboardQuery ¶

type DashboardQuery struct {
	Text          string        `json:"text"`
	EditMode      string        `json:"editMode"` // Either "builder" or "advanced"
	Name          string        `json:"name"`     // Term or phrase that refers to the query
	BuilderConfig BuilderConfig `json:"builderConfig"`
}

DashboardQuery represents a query used in a dashboard cell

type DashboardService ¶

type DashboardService interface {
	// FindDashboardByID returns a single dashboard by ID.
	FindDashboardByID(ctx context.Context, id ID) (*Dashboard, error)

	// FindDashboards returns a list of dashboards that match filter and the total count of matching dashboards.
	// Additional options provide pagination & sorting.
	FindDashboards(ctx context.Context, filter DashboardFilter, opts FindOptions) ([]*Dashboard, int, error)

	// CreateDashboard creates a new dashboard and sets b.ID with the new identifier.
	CreateDashboard(ctx context.Context, b *Dashboard) error

	// UpdateDashboard updates a single dashboard with changeset.
	// Returns the new dashboard state after update.
	UpdateDashboard(ctx context.Context, id ID, upd DashboardUpdate) (*Dashboard, error)

	// AddDashboardCell adds a cell to a dashboard.
	AddDashboardCell(ctx context.Context, id ID, c *Cell, opts AddDashboardCellOptions) error

	// RemoveDashboardCell removes a dashboard.
	RemoveDashboardCell(ctx context.Context, dashboardID, cellID ID) error

	// UpdateDashboardCell replaces the dashboard cell with the provided ID.
	UpdateDashboardCell(ctx context.Context, dashboardID, cellID ID, upd CellUpdate) (*Cell, error)

	// GetDashboardCellView retrieves a dashboard cells view.
	GetDashboardCellView(ctx context.Context, dashboardID, cellID ID) (*View, error)

	// UpdateDashboardCellView retrieves a dashboard cells view.
	UpdateDashboardCellView(ctx context.Context, dashboardID, cellID ID, upd ViewUpdate) (*View, error)

	// DeleteDashboard removes a dashboard by ID.
	DeleteDashboard(ctx context.Context, id ID) error

	// ReplaceDashboardCells replaces all cells in a dashboard
	ReplaceDashboardCells(ctx context.Context, id ID, c []*Cell) error
}

DashboardService represents a service for managing dashboard data.

type DashboardUpdate ¶

type DashboardUpdate struct {
	Name        *string  `json:"name"`
	Description *string  `json:"description"`
	Cells       *[]*Cell `json:"cells"`
}

DashboardUpdate is the patch structure for a dashboard.

func (DashboardUpdate) Apply ¶

func (u DashboardUpdate) Apply(d *Dashboard) error

Apply applies an update to a dashboard.

func (DashboardUpdate) Valid ¶

func (u DashboardUpdate) Valid() *Error

Valid returns an error if the dashboard update is invalid.

type DecimalPlaces ¶

type DecimalPlaces struct {
	IsEnforced bool  `json:"isEnforced"`
	Digits     int32 `json:"digits"`
}

DecimalPlaces indicates whether decimal places should be enforced, and how many digits it should show.

type DeleteService ¶

type DeleteService interface {
	DeleteBucketRangePredicate(ctx context.Context, orgID, bucketID ID, min, max int64, pred Predicate) error
}

DeleteService will delete a bucket from the range and predict.

type Document ¶

type Document struct {
	ID      ID           `json:"id"`
	Meta    DocumentMeta `json:"meta"`
	Content interface{}  `json:"content,omitempty"` // TODO(desa): maybe this needs to be json.Marshaller & json.Unmarshaler
	Labels  []*Label     `json:"labels,omitempty"`  // read only

	// This is needed for authorization.
	// The service that passes documents around will take care of filling it
	// via request parameters or others, as the kv store will take care of
	// filling it once it returns a document.
	// This is not stored in the kv store neither required in the API.
	Organizations map[ID]UserType `json:"-"`
}

Document is a generic structure for stating data.

type DocumentMeta ¶

type DocumentMeta struct {
	Name        string `json:"name"`
	Type        string `json:"type,omitempty"`
	Description string `json:"description,omitempty"`
	Version     string `json:"version,omitempty"`
	CRUDLog
}

DocumentMeta is information that is universal across documents. Ideally data in the meta should be indexed and queryable.

type DocumentService ¶

type DocumentService interface {
	CreateDocumentStore(ctx context.Context, name string) (DocumentStore, error)
	FindDocumentStore(ctx context.Context, name string) (DocumentStore, error)
}

DocumentService is used to create/find instances of document stores.

type DocumentStore ¶

type DocumentStore interface {
	CreateDocument(ctx context.Context, d *Document) error
	FindDocument(ctx context.Context, id ID) (*Document, error)

	FindDocuments(ctx context.Context, orgID ID) ([]*Document, error)
}

DocumentStore is used to perform CRUD operations on documents. It follows an options pattern that allows users to perform actions related to documents in a transactional way.

type Duration ¶

type Duration struct {
	time.Duration
}

Duration is based on time.Duration to embed in any struct.

func (Duration) MarshalJSON ¶

func (d Duration) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler interface.

func (*Duration) UnmarshalJSON ¶

func (d *Duration) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler interface.

type EmptyViewProperties ¶

type EmptyViewProperties struct{}

EmptyViewProperties is visualization that has no values

func (EmptyViewProperties) GetType ¶

func (v EmptyViewProperties) GetType() string

type Error ¶

type Error struct {
	Code string
	Msg  string
	Op   string
	Err  error
}

Error is the error struct of platform.

Errors may have error codes, human-readable messages, and a logical stack trace.

The Code targets automated handlers so that recovery can occur. Msg is used by the system operator to help diagnose and fix the problem. Op and Err chain errors together in a logical stack trace to further help operators.

To create a simple error,

&Error{
    Code:ENotFound,
}

To show where the error happens, add Op.

&Error{
    Code: ENotFound,
    Op: "bolt.FindUserByID"
}

To show an error with a unpredictable value, add the value in Msg.

&Error{
   Code: EConflict,
   Message: fmt.Sprintf("organization with name %s already exist", aName),
}

To show an error wrapped with another error.

&Error{
    Code:EInternal,
    Err: err,
}.

func ErrCorruptID ¶

func ErrCorruptID(err error) *Error

ErrCorruptID means the ID stored in the Store is corrupt.

func ErrFluxParseError ¶

func ErrFluxParseError(err error) *Error

ErrFluxParseError is returned when an error is thrown by Flux.Parse in the task executor

func ErrInternalBucketServiceError ¶

func ErrInternalBucketServiceError(op string, err error) *Error

func ErrInternalOrgServiceError ¶

func ErrInternalOrgServiceError(op string, err error) *Error

func ErrInternalTaskServiceError ¶

func ErrInternalTaskServiceError(err error) *Error

func ErrQueryError ¶

func ErrQueryError(err error) *Error

ErrQueryError is returned when an error is thrown by Query service in the task executor

func ErrResultIteratorError ¶

func ErrResultIteratorError(err error) *Error

ErrResultIteratorError is returned when an error is thrown by exhaustResultIterators in the executor

func ErrRunExecutionError ¶

func ErrRunExecutionError(err error) *Error

func ErrTaskConcurrencyLimitReached ¶

func ErrTaskConcurrencyLimitReached(runsInFront int) *Error

func ErrTaskOptionParse ¶

func ErrTaskOptionParse(err error) *Error

func ErrTaskTimeParse ¶

func ErrTaskTimeParse(err error) *Error

ErrTaskTimeParse an error for time parsing errors

func ErrUnexpectedTaskBucketErr ¶

func ErrUnexpectedTaskBucketErr(err error) *Error

ErrUnexpectedTaskBucketErr a generic error we can use when we rail to retrieve a bucket

func NewError ¶

func NewError(options ...func(*Error)) *Error

NewError returns an instance of an error.

func (*Error) Error ¶

func (e *Error) Error() string

Error implements the error interface by writing out the recursive messages.

func (*Error) MarshalJSON ¶

func (e *Error) MarshalJSON() (result []byte, err error)

MarshalJSON recursively marshals the stack of Err.

func (*Error) UnmarshalJSON ¶

func (e *Error) UnmarshalJSON(b []byte) (err error)

UnmarshalJSON recursively unmarshals the error stack.

type FindOptions ¶

type FindOptions struct {
	Limit      int
	Offset     int
	After      *ID
	SortBy     string
	Descending bool
}

FindOptions represents options passed to all find methods with multiple results.

func DecodeFindOptions ¶

func DecodeFindOptions(r *http.Request) (*FindOptions, error)

DecodeFindOptions returns a FindOptions decoded from http request.

func (*FindOptions) GetLimit ¶

func (f *FindOptions) GetLimit() int

GetLimit returns the resolved limit between then limit boundaries. Given a limit <= 0 it returns the default limit.

func (FindOptions) QueryParams ¶

func (f FindOptions) QueryParams() map[string][]string

QueryParams returns a map containing url query params.

type FluxLanguageService ¶

type FluxLanguageService interface {
	// Parse will take flux source code and produce a package.
	// If there are errors when parsing, the first error is returned.
	// An ast.Package may be returned when a parsing error occurs,
	// but it may be null if parsing didn't even occur.
	Parse(source string) (*ast.Package, error)

	// EvalAST will evaluate and run an AST.
	EvalAST(ctx context.Context, astPkg *ast.Package) ([]interpreter.SideEffect, values.Scope, error)

	// Completer will return a flux completer.
	Completer() complete.Completer
}

FluxLanguageService is a service for interacting with flux code.

type GaugeViewProperties ¶

type GaugeViewProperties struct {
	Type              string           `json:"type"`
	Queries           []DashboardQuery `json:"queries"`
	Prefix            string           `json:"prefix"`
	TickPrefix        string           `json:"tickPrefix"`
	Suffix            string           `json:"suffix"`
	TickSuffix        string           `json:"tickSuffix"`
	ViewColors        []ViewColor      `json:"colors"`
	DecimalPlaces     DecimalPlaces    `json:"decimalPlaces"`
	Note              string           `json:"note"`
	ShowNoteWhenEmpty bool             `json:"showNoteWhenEmpty"`
}

GaugeViewProperties represents options for gauge view in Chronograf

func (GaugeViewProperties) GetType ¶

func (v GaugeViewProperties) GetType() string

type HTTPErrorHandler ¶

type HTTPErrorHandler interface {
	HandleHTTPError(ctx context.Context, err error, w http.ResponseWriter)
}

HTTPErrorHandler is the interface to handle http error.

type HeatmapViewProperties ¶

type HeatmapViewProperties struct {
	Type                       string           `json:"type"`
	Queries                    []DashboardQuery `json:"queries"`
	ViewColors                 []string         `json:"colors"`
	BinSize                    int32            `json:"binSize"`
	XColumn                    string           `json:"xColumn"`
	GenerateXAxisTicks         []string         `json:"generateXAxisTicks"`
	XTotalTicks                int              `json:"xTotalTicks"`
	XTickStart                 float64          `json:"xTickStart"`
	XTickStep                  float64          `json:"xTickStep"`
	YColumn                    string           `json:"yColumn"`
	GenerateYAxisTicks         []string         `json:"generateYAxisTicks"`
	YTotalTicks                int              `json:"yTotalTicks"`
	YTickStart                 float64          `json:"yTickStart"`
	YTickStep                  float64          `json:"yTickStep"`
	XDomain                    []float64        `json:"xDomain,omitempty"`
	YDomain                    []float64        `json:"yDomain,omitempty"`
	XAxisLabel                 string           `json:"xAxisLabel"`
	YAxisLabel                 string           `json:"yAxisLabel"`
	XPrefix                    string           `json:"xPrefix"`
	XSuffix                    string           `json:"xSuffix"`
	YPrefix                    string           `json:"yPrefix"`
	YSuffix                    string           `json:"ySuffix"`
	Note                       string           `json:"note"`
	ShowNoteWhenEmpty          bool             `json:"showNoteWhenEmpty"`
	TimeFormat                 string           `json:"timeFormat"`
	LegendColorizeRows         bool             `json:"legendColorizeRows"`
	LegendOpacity              float64          `json:"legendOpacity"`
	LegendOrientationThreshold int              `json:"legendOrientationThreshold"`
}

HeatmapViewProperties represents options for heatmap view in Chronograf

func (HeatmapViewProperties) GetType ¶

func (v HeatmapViewProperties) GetType() string

type HistogramViewProperties ¶

type HistogramViewProperties struct {
	Type                       string           `json:"type"`
	Queries                    []DashboardQuery `json:"queries"`
	ViewColors                 []ViewColor      `json:"colors"`
	XColumn                    string           `json:"xColumn"`
	FillColumns                []string         `json:"fillColumns"`
	XDomain                    []float64        `json:"xDomain,omitempty"`
	XAxisLabel                 string           `json:"xAxisLabel"`
	Position                   string           `json:"position"`
	BinCount                   int              `json:"binCount"`
	Note                       string           `json:"note"`
	ShowNoteWhenEmpty          bool             `json:"showNoteWhenEmpty"`
	LegendColorizeRows         bool             `json:"legendColorizeRows"`
	LegendOpacity              float64          `json:"legendOpacity"`
	LegendOrientationThreshold int              `json:"legendOrientationThreshold"`
}

HistogramViewProperties represents options for histogram view in Chronograf

func (HistogramViewProperties) GetType ¶

func (v HistogramViewProperties) GetType() string

type ID ¶

type ID uint64

ID is a unique identifier.

Its zero value is not a valid ID.

func IDFromString ¶

func IDFromString(str string) (*ID, error)

IDFromString creates an ID from a given string.

It errors if the input string does not match a valid ID.

func InvalidID ¶

func InvalidID() ID

InvalidID returns a zero ID.

func (*ID) Decode ¶

func (i *ID) Decode(b []byte) error

Decode parses b as a hex-encoded byte-slice-string.

It errors if the input byte slice does not have the correct length or if it contains all zeros.

func (*ID) DecodeFromString ¶

func (i *ID) DecodeFromString(s string) error

DecodeFromString parses s as a hex-encoded string.

func (ID) Encode ¶

func (i ID) Encode() ([]byte, error)

Encode converts ID to a hex-encoded byte-slice-string.

It errors if the receiving ID holds its zero value.

func (ID) GoString ¶

func (i ID) GoString() string

GoString formats the ID the same as the String method. Without this, when using the %#v verb, an ID would be printed as a uint64, so you would see e.g. 0x2def021097c6000 instead of 02def021097c6000 (note the leading 0x, which means the former doesn't show up in searches for the latter).

func (ID) MarshalText ¶

func (i ID) MarshalText() ([]byte, error)

MarshalText encodes i as text. Providing this method is a fallback for json.Marshal, with the added benefit that IDs encoded as map keys will be the expected string encoding, rather than the effective fmt.Sprintf("%d", i) that json.Marshal uses by default for integer types.

func (ID) String ¶

func (i ID) String() string

String returns the ID as a hex encoded string.

Returns an empty string in the case the ID is invalid.

func (*ID) UnmarshalText ¶

func (i *ID) UnmarshalText(b []byte) error

UnmarshalText decodes i from a byte slice. Providing this method is also a fallback for json.Unmarshal, also relevant when IDs are used as map keys.

func (ID) Valid ¶

func (i ID) Valid() bool

Valid checks whether the receiving ID is a valid one or not.

type IDGenerator ¶

type IDGenerator interface {
	// ID creates unique byte slice ID.
	ID() ID
}

IDGenerator represents a generator for IDs.

type KeyValueLog ¶

type KeyValueLog interface {
	// AddLogEntry adds an entry (v,t) to the log defined for the key k.
	AddLogEntry(ctx context.Context, k []byte, v []byte, t time.Time) error

	// ForEachLogEntry iterates through all the log entries at key k and applies the function fn for each record.
	ForEachLogEntry(ctx context.Context, k []byte, opts FindOptions, fn func(v []byte, t time.Time) error) error

	// FirstLogEntry is used to retrieve the first entry in the log at key k.
	FirstLogEntry(ctx context.Context, k []byte) ([]byte, time.Time, error)

	// LastLogEntry is used to retrieve the last entry in the log at key k.
	LastLogEntry(ctx context.Context, k []byte) ([]byte, time.Time, error)
}

KeyValueLog is a generic type logs key-value pairs. This interface is intended to be used to construct other higher-level log-like resources such as an oplog or audit log.

The idea is to create a log who values can be accessed at the key k: k -> [(v0,t0) (v1,t1) ... (vn,tn)]

Logs may be retrieved in ascending or descending time order and support limits and offsets.

type Label ¶

type Label struct {
	ID         ID                `json:"id,omitempty"`
	OrgID      ID                `json:"orgID,omitempty"`
	Name       string            `json:"name"`
	Properties map[string]string `json:"properties,omitempty"`
}

Label is a tag set on a resource, typically used for filtering on a UI.

func (*Label) Validate ¶

func (l *Label) Validate() error

Validate returns an error if the label is invalid.

type LabelFilter ¶

type LabelFilter struct {
	Name  string
	OrgID *ID
}

LabelFilter represents a set of filters that restrict the returned results.

type LabelMapping ¶

type LabelMapping struct {
	LabelID      ID `json:"labelID"`
	ResourceID   ID `json:"resourceID,omitempty"`
	ResourceType `json:"resourceType"`
}

LabelMapping is used to map resource to its labels. It should not be shared directly over the HTTP API.

func (*LabelMapping) Validate ¶

func (l *LabelMapping) Validate() error

Validate returns an error if the mapping is invalid.

type LabelMappingFilter ¶

type LabelMappingFilter struct {
	ResourceID ID
	ResourceType
}

LabelMappingFilter represents a set of filters that restrict the returned results.

type LabelService ¶

type LabelService interface {
	// FindLabelByID a single label by ID.
	FindLabelByID(ctx context.Context, id ID) (*Label, error)

	// FindLabels returns a list of labels that match a filter
	FindLabels(ctx context.Context, filter LabelFilter, opt ...FindOptions) ([]*Label, error)

	// FindResourceLabels returns a list of labels that belong to a resource
	FindResourceLabels(ctx context.Context, filter LabelMappingFilter) ([]*Label, error)

	// CreateLabel creates a new label
	CreateLabel(ctx context.Context, l *Label) error

	// CreateLabelMapping maps a resource to an existing label
	CreateLabelMapping(ctx context.Context, m *LabelMapping) error

	// UpdateLabel updates a label with a changeset.
	UpdateLabel(ctx context.Context, id ID, upd LabelUpdate) (*Label, error)

	// DeleteLabel deletes a label
	DeleteLabel(ctx context.Context, id ID) error

	// DeleteLabelMapping deletes a label mapping
	DeleteLabelMapping(ctx context.Context, m *LabelMapping) error
}

LabelService represents a service for managing resource labels

type LabelUpdate ¶

type LabelUpdate struct {
	Name       string            `json:"name,omitempty"`
	Properties map[string]string `json:"properties,omitempty"`
}

LabelUpdate represents a changeset for a label. Only the properties specified are updated.

type Lease ¶

type Lease interface {
	// TTL returns the duration of time remaining before the lease expires.
	TTL(context.Context) (time.Duration, error)

	// Release terminates ownership of the semaphore by revoking the lease.
	Release(context.Context) error

	// KeepAlive extends the lease back to the original TTL.
	KeepAlive(context.Context) error
}

A Lease represents ownership over a semaphore. It gives the owner the ability to extend ownership over the semaphore or release ownership of the semaphore.

type Legend ¶

type Legend struct {
	Type        string `json:"type,omitempty"`
	Orientation string `json:"orientation,omitempty"`
}

Legend represents the encoding of data into a legend

type Limit ¶

type Limit struct {
	Rate int `json:"limit,omitempty"`
	// every seconds.
	Every int `json:"limitEvery,omitempty"`
}

Limit don't notify me more than <limit> times every <limitEvery> seconds. If set, limit cannot be empty.

type LinePlusSingleStatProperties ¶

type LinePlusSingleStatProperties struct {
	Queries                    []DashboardQuery `json:"queries"`
	Axes                       map[string]Axis  `json:"axes"`
	Type                       string           `json:"type"`
	Legend                     Legend           `json:"legend"`
	ViewColors                 []ViewColor      `json:"colors"`
	Prefix                     string           `json:"prefix"`
	Suffix                     string           `json:"suffix"`
	DecimalPlaces              DecimalPlaces    `json:"decimalPlaces"`
	Note                       string           `json:"note"`
	ShowNoteWhenEmpty          bool             `json:"showNoteWhenEmpty"`
	XColumn                    string           `json:"xColumn"`
	GenerateXAxisTicks         []string         `json:"generateXAxisTicks"`
	XTotalTicks                int              `json:"xTotalTicks"`
	XTickStart                 float64          `json:"xTickStart"`
	XTickStep                  float64          `json:"xTickStep"`
	YColumn                    string           `json:"yColumn"`
	GenerateYAxisTicks         []string         `json:"generateYAxisTicks"`
	YTotalTicks                int              `json:"yTotalTicks"`
	YTickStart                 float64          `json:"yTickStart"`
	YTickStep                  float64          `json:"yTickStep"`
	ShadeBelow                 bool             `json:"shadeBelow"`
	Position                   string           `json:"position"`
	TimeFormat                 string           `json:"timeFormat"`
	HoverDimension             string           `json:"hoverDimension"`
	LegendColorizeRows         bool             `json:"legendColorizeRows"`
	LegendOpacity              float64          `json:"legendOpacity"`
	LegendOrientationThreshold int              `json:"legendOrientationThreshold"`
}

LinePlusSingleStatProperties represents options for line plus single stat view in Chronograf

func (LinePlusSingleStatProperties) GetType ¶

type Log ¶

type Log struct {
	RunID   ID     `json:"runID,omitempty"`
	Time    string `json:"time"`
	Message string `json:"message"`
}

Log represents a link to a log resource

func (Log) String ¶

func (l Log) String() string

type LogColumnSetting ¶

type LogColumnSetting struct {
	Type  string `json:"type"`
	Value string `json:"value"`
	Name  string `json:"name,omitempty"`
}

LogColumnSetting represent the settings for a specific column of a Log Viewer.

type LogFilter ¶

type LogFilter struct {
	// Task ID is required.
	Task ID

	// The optional Run ID limits logs to a single run.
	Run *ID
}

LogFilter represents a set of filters that restrict the returned log results.

type LogViewProperties ¶

type LogViewProperties struct {
	Type    string            `json:"type"`
	Columns []LogViewerColumn `json:"columns"`
}

LogViewProperties represents options for log viewer in Chronograf.

func (LogViewProperties) GetType ¶

func (v LogViewProperties) GetType() string

type LogViewerColumn ¶

type LogViewerColumn struct {
	Name     string             `json:"name"`
	Position int32              `json:"position"`
	Settings []LogColumnSetting `json:"settings"`
}

LogViewerColumn represents a specific column in a Log Viewer.

type LookupService ¶

type LookupService interface {
	// FindResourceName returns the name for the resource and ID.
	FindResourceName(ctx context.Context, resource ResourceType, id ID) (string, error)
}

LookupService provides field lookup for the resource and ID.

type Manifest ¶

type Manifest struct {
	KV    ManifestKVEntry `json:"kv"`
	Files []ManifestEntry `json:"files"`
}

Manifest lists the KV and shard file information contained in the backup.

func (*Manifest) Size ¶

func (m *Manifest) Size() int64

Size returns the size of the manifest.

type ManifestEntry ¶

type ManifestEntry struct {
	OrganizationID   string    `json:"organizationID"`
	OrganizationName string    `json:"organizationName"`
	BucketID         string    `json:"bucketID"`
	BucketName       string    `json:"bucketName"`
	ShardID          uint64    `json:"shardID"`
	FileName         string    `json:"fileName"`
	Size             int64     `json:"size"`
	LastModified     time.Time `json:"lastModified"`
}

ManifestEntry contains the data information for a backed up shard.

type ManifestKVEntry ¶

type ManifestKVEntry struct {
	FileName string `json:"fileName"`
	Size     int64  `json:"size"`
}

ManifestKVEntry contains the KV store information for a backup.

type MappingType ¶

type MappingType uint8

func (MappingType) MarshalJSON ¶

func (mt MappingType) MarshalJSON() ([]byte, error)

func (MappingType) String ¶

func (mt MappingType) String() string

func (*MappingType) UnmarshalJSON ¶

func (mt *MappingType) UnmarshalJSON(b []byte) error

func (MappingType) Valid ¶

func (mt MappingType) Valid() error

type MarkdownViewProperties ¶

type MarkdownViewProperties struct {
	Type string `json:"type"`
	Note string `json:"note"`
}

func (MarkdownViewProperties) GetType ¶

func (v MarkdownViewProperties) GetType() string

type MosaicViewProperties ¶

type MosaicViewProperties struct {
	Type                       string           `json:"type"`
	Queries                    []DashboardQuery `json:"queries"`
	ViewColors                 []string         `json:"colors"`
	FillColumns                []string         `json:"fillColumns"`
	XColumn                    string           `json:"xColumn"`
	GenerateXAxisTicks         []string         `json:"generateXAxisTicks"`
	XTotalTicks                int              `json:"xTotalTicks"`
	XTickStart                 float64          `json:"xTickStart"`
	XTickStep                  float64          `json:"xTickStep"`
	YSeriesColumns             []string         `json:"ySeriesColumns"`
	XDomain                    []float64        `json:"xDomain,omitempty"`
	YDomain                    []float64        `json:"yDomain,omitempty"`
	XAxisLabel                 string           `json:"xAxisLabel"`
	YAxisLabel                 string           `json:"yAxisLabel"`
	XPrefix                    string           `json:"xPrefix"`
	XSuffix                    string           `json:"xSuffix"`
	YPrefix                    string           `json:"yPrefix"`
	YSuffix                    string           `json:"ySuffix"`
	Note                       string           `json:"note"`
	ShowNoteWhenEmpty          bool             `json:"showNoteWhenEmpty"`
	TimeFormat                 string           `json:"timeFormat"`
	LegendColorizeRows         bool             `json:"legendColorizeRows"`
	LegendOpacity              float64          `json:"legendOpacity"`
	LegendOrientationThreshold int              `json:"legendOrientationThreshold"`
}

MosaicViewProperties represents options for mosaic view in Chronograf

func (MosaicViewProperties) GetType ¶

func (v MosaicViewProperties) GetType() string

type NotificationEndpoint ¶

type NotificationEndpoint interface {
	Valid() error
	Type() string
	json.Marshaler
	CRUDLogSetter
	SetID(id ID)
	SetOrgID(id ID)
	SetName(name string)
	SetDescription(description string)
	SetStatus(status Status)

	GetID() ID
	GetCRUDLog() CRUDLog
	GetOrgID() ID
	GetName() string
	GetDescription() string
	GetStatus() Status
	// SecretFields return available secret fields.
	SecretFields() []SecretField
	// BackfillSecretKeys fill back fill the secret field key during the unmarshalling
	// if value of that secret field is not nil.
	BackfillSecretKeys()
}

NotificationEndpoint is the configuration describing how to call a 3rd party service. E.g. Slack, Pagerduty

type NotificationEndpointFilter ¶

type NotificationEndpointFilter struct {
	ID    *ID
	OrgID *ID
	Org   *string
	UserResourceMappingFilter
}

NotificationEndpointFilter represents a set of filter that restrict the returned notification endpoints.

func (NotificationEndpointFilter) QueryParams ¶

func (f NotificationEndpointFilter) QueryParams() map[string][]string

QueryParams Converts NotificationEndpointFilter fields to url query params.

type NotificationEndpointService ¶

type NotificationEndpointService interface {
	// FindNotificationEndpointByID returns a single notification endpoint by ID.
	FindNotificationEndpointByID(ctx context.Context, id ID) (NotificationEndpoint, error)

	// FindNotificationEndpoints returns a list of notification endpoints that match filter and the total count of matching notification endpoints.
	// Additional options provide pagination & sorting.
	FindNotificationEndpoints(ctx context.Context, filter NotificationEndpointFilter, opt ...FindOptions) ([]NotificationEndpoint, int, error)

	// CreateNotificationEndpoint creates a new notification endpoint and sets b.ID with the new identifier.
	CreateNotificationEndpoint(ctx context.Context, ne NotificationEndpoint, userID ID) error

	// UpdateNotificationEndpoint updates a single notification endpoint.
	// Returns the new notification endpoint after update.
	UpdateNotificationEndpoint(ctx context.Context, id ID, nr NotificationEndpoint, userID ID) (NotificationEndpoint, error)

	// PatchNotificationEndpoint updates a single  notification endpoint with changeset.
	// Returns the new notification endpoint state after update.
	PatchNotificationEndpoint(ctx context.Context, id ID, upd NotificationEndpointUpdate) (NotificationEndpoint, error)

	// DeleteNotificationEndpoint removes a notification endpoint by ID, returns secret fields, orgID for further deletion.
	DeleteNotificationEndpoint(ctx context.Context, id ID) (flds []SecretField, orgID ID, err error)
}

NotificationEndpointService represents a service for managing notification endpoints.

type NotificationEndpointUpdate ¶

type NotificationEndpointUpdate struct {
	Name        *string `json:"name,omitempty"`
	Description *string `json:"description,omitempty"`
	Status      *Status `json:"status,omitempty"`
}

NotificationEndpointUpdate is the set of upgrade fields for patch request.

func (*NotificationEndpointUpdate) Valid ¶

func (n *NotificationEndpointUpdate) Valid() error

Valid will verify if the NotificationEndpointUpdate is valid.

type NotificationRule ¶

type NotificationRule interface {
	Valid() error
	Type() string
	json.Marshaler
	CRUDLogSetter
	SetID(id ID)
	SetOrgID(id ID)
	SetName(name string)
	SetDescription(description string)
	GetID() ID
	GetCRUDLog() CRUDLog
	GetOrgID() ID
	GetName() string
	GetDescription() string
	SetOwnerID(id ID)
	ClearPrivateData()
	GetOwnerID() ID
	SetTaskID(id ID)
	GetTaskID() ID
	GetEndpointID() ID
	GetLimit() *Limit
	GenerateFlux(NotificationEndpoint) (string, error)
	MatchesTags(tags []Tag) bool
}

NotificationRule is a *Query* of a *Status Bucket* that returns the *Status*. When warranted by the rules, sends a *Message* to a 3rd Party using the *Notification Endpoint* and stores a receipt in the *Notifications Bucket*.

type NotificationRuleCreate ¶

type NotificationRuleCreate struct {
	NotificationRule
	Status Status `json:"status"`
}

NotificationRuleCreate is the struct providing data to create a Notification Rule.

type NotificationRuleFilter ¶

type NotificationRuleFilter struct {
	OrgID        *ID
	Organization *string
	Tags         []Tag
	UserResourceMappingFilter
}

NotificationRuleFilter represents a set of filter that restrict the returned notification rules.

func (NotificationRuleFilter) QueryParams ¶

func (f NotificationRuleFilter) QueryParams() map[string][]string

QueryParams Converts NotificationRuleFilter fields to url query params.

type NotificationRuleStore ¶

type NotificationRuleStore interface {
	// FindNotificationRuleByID returns a single notification rule by ID.
	FindNotificationRuleByID(ctx context.Context, id ID) (NotificationRule, error)

	// FindNotificationRules returns a list of notification rules that match filter and the total count of matching notification rules.
	// Additional options provide pagination & sorting.
	FindNotificationRules(ctx context.Context, filter NotificationRuleFilter, opt ...FindOptions) ([]NotificationRule, int, error)

	// CreateNotificationRule creates a new notification rule and sets b.ID with the new identifier.
	CreateNotificationRule(ctx context.Context, nr NotificationRuleCreate, userID ID) error

	// UpdateNotificationRuleUpdateNotificationRule updates a single notification rule.
	// Returns the new notification rule after update.
	UpdateNotificationRule(ctx context.Context, id ID, nr NotificationRuleCreate, userID ID) (NotificationRule, error)

	// PatchNotificationRule updates a single  notification rule with changeset.
	// Returns the new notification rule state after update.
	PatchNotificationRule(ctx context.Context, id ID, upd NotificationRuleUpdate) (NotificationRule, error)

	// DeleteNotificationRule removes a notification rule by ID.
	DeleteNotificationRule(ctx context.Context, id ID) error
}

NotificationRuleStore represents a service for managing notification rule.

type NotificationRuleUpdate ¶

type NotificationRuleUpdate struct {
	Name        *string `json:"name,omitempty"`
	Description *string `json:"description,omitempty"`
	Status      *Status `json:"status,omitempty"`
}

NotificationRuleUpdate is the set of upgrade fields for patch request.

func (*NotificationRuleUpdate) Valid ¶

func (n *NotificationRuleUpdate) Valid() error

Valid will verify if the NotificationRuleUpdate is valid.

type OnboardingRequest ¶

type OnboardingRequest struct {
	User                      string        `json:"username"`
	Password                  string        `json:"password"`
	Org                       string        `json:"org"`
	Bucket                    string        `json:"bucket"`
	RetentionPeriodSeconds    int64         `json:"retentionPeriodSeconds,omitempty"`
	RetentionPeriodDeprecated time.Duration `json:"retentionPeriodHrs,omitempty"`
	Token                     string        `json:"token,omitempty"`
}

OnboardingRequest is the request to setup defaults.

func (*OnboardingRequest) RetentionPeriod ¶

func (r *OnboardingRequest) RetentionPeriod() time.Duration

func (*OnboardingRequest) Valid ¶

func (r *OnboardingRequest) Valid() error

type OnboardingResults ¶

type OnboardingResults struct {
	User   *User          `json:"user"`
	Org    *Organization  `json:"org"`
	Bucket *Bucket        `json:"bucket"`
	Auth   *Authorization `json:"auth"`
}

OnboardingResults is a group of elements required for first run.

type OnboardingService ¶

type OnboardingService interface {
	// IsOnboarding determine if onboarding request is allowed.
	IsOnboarding(ctx context.Context) (bool, error)

	// OnboardInitialUser OnboardingResults.
	OnboardInitialUser(ctx context.Context, req *OnboardingRequest) (*OnboardingResults, error)

	// OnboardUser creates a new user/org/buckets
	OnboardUser(ctx context.Context, req *OnboardingRequest) (*OnboardingResults, error)
}

OnboardingService represents a service for the first run.

type OperationLogEntry ¶

type OperationLogEntry struct {
	Description string    `json:"description"`
	UserID      ID        `json:"userID,omitempty"`
	Time        time.Time `json:"time,omitempty"`
}

OperationLogEntry is a record in an operation log.

type Operator ¶

type Operator int

Operator is an Enum value of operators.

const (
	Equal Operator = iota
	NotEqual
	RegexEqual
	NotRegexEqual
)

operators

func ToOperator ¶

func ToOperator(s string) (Operator, bool)

ToOperator converts a string into its equivalent Operator.

func (Operator) MarshalJSON ¶

func (op Operator) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshal interface.

func (Operator) String ¶

func (op Operator) String() string

String returns the string value of the operator.

func (*Operator) UnmarshalJSON ¶

func (op *Operator) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler interface.

func (Operator) Valid ¶

func (op Operator) Valid() error

Valid returns invalid error if the operator is invalid.

type Organization ¶

type Organization struct {
	ID          ID     `json:"id,omitempty"`
	Name        string `json:"name"`
	Description string `json:"description"`
	CRUDLog
}

Organization is an organization. 🎉

type OrganizationFilter ¶

type OrganizationFilter struct {
	Name   *string
	ID     *ID
	UserID *ID
}

OrganizationFilter represents a set of filter that restrict the returned results.

type OrganizationOperationLogService ¶

type OrganizationOperationLogService interface {
	// GetOrganizationOperationLog retrieves the operation log for the org with the provided id.
	GetOrganizationOperationLog(ctx context.Context, id ID, opts FindOptions) ([]*OperationLogEntry, int, error)
}

OrganizationOperationLogService is an interface for retrieving the operation log for an org.

type OrganizationService ¶

type OrganizationService interface {
	// Returns a single organization by ID.
	FindOrganizationByID(ctx context.Context, id ID) (*Organization, error)

	// Returns the first organization that matches filter.
	FindOrganization(ctx context.Context, filter OrganizationFilter) (*Organization, error)

	// Returns a list of organizations that match filter and the total count of matching organizations.
	// Additional options provide pagination & sorting.
	FindOrganizations(ctx context.Context, filter OrganizationFilter, opt ...FindOptions) ([]*Organization, int, error)

	// Creates a new organization and sets b.ID with the new identifier.
	CreateOrganization(ctx context.Context, b *Organization) error

	// Updates a single organization with changeset.
	// Returns the new organization state after update.
	UpdateOrganization(ctx context.Context, id ID, upd OrganizationUpdate) (*Organization, error)

	// Removes a organization by ID.
	DeleteOrganization(ctx context.Context, id ID) error
}

OrganizationService represents a service for managing organization data.

type OrganizationUpdate ¶

type OrganizationUpdate struct {
	Name        *string
	Description *string `json:"description,omitempty"`
}

OrganizationUpdate represents updates to a organization. Only fields which are set are updated.

type PagingFilter ¶

type PagingFilter interface {
	// QueryParams returns a map containing url query params.
	QueryParams() map[string][]string
}

PagingFilter represents a filter containing url query params.

type PagingLinks struct {
	Prev string `json:"prev,omitempty"`
	Self string `json:"self"`
	Next string `json:"next,omitempty"`
}

PagingLinks represents paging links.

func NewPagingLinks(basePath string, opts FindOptions, f PagingFilter, num int) *PagingLinks

NewPagingLinks returns a PagingLinks. num is the number of returned results.

type PasswordsService ¶

type PasswordsService interface {
	// SetPassword overrides the password of a known user.
	SetPassword(ctx context.Context, userID ID, password string) error
	// ComparePassword checks if the password matches the password recorded.
	// Passwords that do not match return errors.
	ComparePassword(ctx context.Context, userID ID, password string) error
	// CompareAndSetPassword checks the password and if they match
	// updates to the new password.
	CompareAndSetPassword(ctx context.Context, userID ID, old, new string) error
}

PasswordsService is the service for managing basic auth passwords.

type Permission ¶

type Permission struct {
	Action   Action   `json:"action"`
	Resource Resource `json:"resource"`
}

Permission defines an action and a resource.

func MePermissions ¶

func MePermissions(userID ID) []Permission

MePermissions is the permission to read/write myself.

func MemberBucketPermission ¶

func MemberBucketPermission(bucketID ID) Permission

MemberPermissions are the default permissions for those who can see a resource.

func MemberPermissions ¶

func MemberPermissions(orgID ID) []Permission

MemberPermissions are the default permissions for those who can see a resource.

func NewGlobalPermission ¶

func NewGlobalPermission(a Action, rt ResourceType) (*Permission, error)

NewGlobalPermission constructs a global permission capable of accessing any resource of type rt.

func NewPermission ¶

func NewPermission(a Action, rt ResourceType, orgID ID) (*Permission, error)

NewPermission returns a permission with provided arguments.

func NewPermissionAtID ¶

func NewPermissionAtID(id ID, a Action, rt ResourceType, orgID ID) (*Permission, error)

NewPermissionAtID creates a permission with the provided arguments.

func NewResourcePermission ¶

func NewResourcePermission(a Action, rt ResourceType, rid ID) (*Permission, error)

NewResourcePermission returns a permission with provided arguments.

func OperPermissions ¶

func OperPermissions() []Permission

OperPermissions are the default permissions for those who setup the application.

func OwnerPermissions ¶

func OwnerPermissions(orgID ID) []Permission

OwnerPermissions are the default permissions for those who own a resource.

func ReadAllPermissions ¶

func ReadAllPermissions() []Permission

ReadAllPermissions represents permission to read all data and metadata. Like OperPermissions, but allows read-only users.

func (Permission) Matches ¶

func (p Permission) Matches(perm Permission) bool

Matches returns whether or not one permission matches the other.

func (Permission) String ¶

func (p Permission) String() string

func (*Permission) Valid ¶

func (p *Permission) Valid() error

Valid checks if there the resource and action provided is known.

type PermissionSet ¶

type PermissionSet []Permission

func (PermissionSet) Allowed ¶

func (ps PermissionSet) Allowed(p Permission) bool

type Predicate ¶

type Predicate interface {
	Clone() Predicate
	Matches(key []byte) bool
	Marshal() ([]byte, error)
}

Predicate is something that can match on a series key.

type RealTimeGenerator ¶

type RealTimeGenerator struct{}

RealTimeGenerator will generate the real time.

func (RealTimeGenerator) Now ¶

func (g RealTimeGenerator) Now() time.Time

Now returns the current time.

type RenamableField ¶

type RenamableField struct {
	InternalName string `json:"internalName"`
	DisplayName  string `json:"displayName"`
	Visible      bool   `json:"visible"`
}

RenamableField is a column/row field in a DashboardView of type Table

type RequestStillQueuedError ¶

type RequestStillQueuedError struct {
	// Unix timestamps matching existing request's start and end.
	Start, End int64
}

RequestStillQueuedError is returned when attempting to retry a run which has not yet completed.

func ParseRequestStillQueuedError ¶

func ParseRequestStillQueuedError(msg string) *RequestStillQueuedError

ParseRequestStillQueuedError attempts to parse a RequestStillQueuedError from msg. If msg is formatted correctly, the resultant error is returned; otherwise it returns nil.

func (RequestStillQueuedError) Error ¶

func (e RequestStillQueuedError) Error() string

type Resource ¶

type Resource struct {
	Type  ResourceType `json:"type"`
	ID    *ID          `json:"id,omitempty"`
	OrgID *ID          `json:"orgID,omitempty"`
}

Resource is an authorizable resource.

func (Resource) String ¶

func (r Resource) String() string

String stringifies a resource

func (Resource) Valid ¶

func (r Resource) Valid() (err error)

Valid checks if the resource type is a member of the ResourceType enum.

type ResourceType ¶

type ResourceType string

ResourceType is an enum defining all resource types that have a permission model in platform

func (ResourceType) Valid ¶

func (t ResourceType) Valid() (err error)

Valid checks if the resource type is a member of the ResourceType enum.

type RestoreService ¶

type RestoreService interface {
	// RestoreKVStore restores & replaces metadata database.
	RestoreKVStore(ctx context.Context, r io.Reader) error

	// RestoreKVStore restores the metadata database.
	RestoreBucket(ctx context.Context, id ID, rpiData []byte) (shardIDMap map[uint64]uint64, err error)

	// RestoreShard uploads a backup file for a single shard.
	RestoreShard(ctx context.Context, shardID uint64, r io.Reader) error
}

RestoreService represents the data restore functions of InfluxDB.

type Run ¶

type Run struct {
	ID           ID        `json:"id,omitempty"`
	TaskID       ID        `json:"taskID"`
	Status       string    `json:"status"`
	ScheduledFor time.Time `json:"scheduledFor"`          // ScheduledFor is the Now time used in the task's query
	RunAt        time.Time `json:"runAt"`                 // RunAt is the time the task is scheduled to be run, which is ScheduledFor + Offset
	StartedAt    time.Time `json:"startedAt,omitempty"`   // StartedAt is the time the executor begins running the task
	FinishedAt   time.Time `json:"finishedAt,omitempty"`  // FinishedAt is the time the executor finishes running the task
	RequestedAt  time.Time `json:"requestedAt,omitempty"` // RequestedAt is the time the coordinator told the scheduler to schedule the task
	Log          []Log     `json:"log,omitempty"`
}

Run is a record createId when a run of a task is scheduled.

type RunFilter ¶

type RunFilter struct {
	// Task ID is required for listing runs.
	Task ID

	After      *ID
	Limit      int
	AfterTime  string
	BeforeTime string
}

RunFilter represents a set of filters that restrict the returned results

type RunStatus ¶

type RunStatus int
const (
	RunStarted RunStatus = iota
	RunSuccess
	RunFail
	RunCanceled
	RunScheduled
)

func (RunStatus) String ¶

func (r RunStatus) String() string

type ScatterViewProperties ¶

type ScatterViewProperties struct {
	Type                       string           `json:"type"`
	Queries                    []DashboardQuery `json:"queries"`
	ViewColors                 []string         `json:"colors"`
	FillColumns                []string         `json:"fillColumns"`
	SymbolColumns              []string         `json:"symbolColumns"`
	XColumn                    string           `json:"xColumn"`
	GenerateXAxisTicks         []string         `json:"generateXAxisTicks"`
	XTotalTicks                int              `json:"xTotalTicks"`
	XTickStart                 float64          `json:"xTickStart"`
	XTickStep                  float64          `json:"xTickStep"`
	YColumn                    string           `json:"yColumn"`
	GenerateYAxisTicks         []string         `json:"generateYAxisTicks"`
	YTotalTicks                int              `json:"yTotalTicks"`
	YTickStart                 float64          `json:"yTickStart"`
	YTickStep                  float64          `json:"yTickStep"`
	XDomain                    []float64        `json:"xDomain,omitempty"`
	YDomain                    []float64        `json:"yDomain,omitempty"`
	XAxisLabel                 string           `json:"xAxisLabel"`
	YAxisLabel                 string           `json:"yAxisLabel"`
	XPrefix                    string           `json:"xPrefix"`
	XSuffix                    string           `json:"xSuffix"`
	YPrefix                    string           `json:"yPrefix"`
	YSuffix                    string           `json:"ySuffix"`
	Note                       string           `json:"note"`
	ShowNoteWhenEmpty          bool             `json:"showNoteWhenEmpty"`
	TimeFormat                 string           `json:"timeFormat"`
	LegendColorizeRows         bool             `json:"legendColorizeRows"`
	LegendOpacity              float64          `json:"legendOpacity"`
	LegendOrientationThreshold int              `json:"legendOrientationThreshold"`
}

ScatterViewProperties represents options for scatter view in Chronograf

func (ScatterViewProperties) GetType ¶

func (v ScatterViewProperties) GetType() string

type SchemeV1 ¶

type SchemeV1 string

SchemeV1 is an enumeration of supported authorization types

const (
	// SchemeV1Basic indicates the credentials came from an Authorization header using the BASIC scheme
	SchemeV1Basic SchemeV1 = "basic"

	// SchemeV1Token indicates the credentials came from an Authorization header using the Token scheme
	SchemeV1Token SchemeV1 = "token"

	// SchemeV1URL indicates the credentials came from the u and p query parameters
	SchemeV1URL SchemeV1 = "url"
)

type ScraperTarget ¶

type ScraperTarget struct {
	ID            ID          `json:"id,omitempty"`
	Name          string      `json:"name"`
	Type          ScraperType `json:"type"`
	URL           string      `json:"url"`
	OrgID         ID          `json:"orgID,omitempty"`
	BucketID      ID          `json:"bucketID,omitempty"`
	AllowInsecure bool        `json:"allowInsecure,omitempty"`
}

ScraperTarget is a target to scrape

type ScraperTargetFilter ¶

type ScraperTargetFilter struct {
	IDs   map[ID]bool `json:"ids"`
	Name  *string     `json:"name"`
	OrgID *ID         `json:"orgID"`
	Org   *string     `json:"org"`
}

ScraperTargetFilter represents a set of filter that restrict the returned results.

type ScraperTargetStoreService ¶

type ScraperTargetStoreService interface {
	ListTargets(ctx context.Context, filter ScraperTargetFilter) ([]ScraperTarget, error)
	AddTarget(ctx context.Context, t *ScraperTarget, userID ID) error
	GetTargetByID(ctx context.Context, id ID) (*ScraperTarget, error)
	RemoveTarget(ctx context.Context, id ID) error
	UpdateTarget(ctx context.Context, t *ScraperTarget, userID ID) (*ScraperTarget, error)
}

ScraperTargetStoreService defines the crud service for ScraperTarget.

type ScraperType ¶

type ScraperType string

ScraperType defines the scraper methods.

type SecretField ¶

type SecretField struct {
	Key   string  `json:"key"`
	Value *string `json:"value,omitempty"`
}

SecretField contains a key string, and value pointer.

func (SecretField) MarshalJSON ¶

func (s SecretField) MarshalJSON() ([]byte, error)

MarshalJSON implement the json marshaler interface.

func (SecretField) String ¶

func (s SecretField) String() string

String returns the key of the secret.

func (*SecretField) UnmarshalJSON ¶

func (s *SecretField) UnmarshalJSON(b []byte) error

UnmarshalJSON implement the json unmarshaler interface.

type SecretService ¶

type SecretService interface {
	// LoadSecret retrieves the secret value v found at key k for organization orgID.
	LoadSecret(ctx context.Context, orgID ID, k string) (string, error)

	// GetSecretKeys retrieves all secret keys that are stored for the organization orgID.
	GetSecretKeys(ctx context.Context, orgID ID) ([]string, error)

	// PutSecret stores the secret pair (k,v) for the organization orgID.
	PutSecret(ctx context.Context, orgID ID, k string, v string) error

	// PutSecrets puts all provided secrets and overwrites any previous values.
	PutSecrets(ctx context.Context, orgID ID, m map[string]string) error

	// PatchSecrets patches all provided secrets and updates any previous values.
	PatchSecrets(ctx context.Context, orgID ID, m map[string]string) error

	// DeleteSecret removes a single secret from the secret store.
	DeleteSecret(ctx context.Context, orgID ID, ks ...string) error
}

SecretService a service for storing and retrieving secrets.

type Semaphore ¶

type Semaphore interface {
	// TryAcquire attempts to acquire ownership of the semaphore. TryAcquire
	// must not block. Failure to get ownership of the semaphore should be
	// signalled to the caller via the return of the ErrNoAcquire error.
	TryAcquire(ctx context.Context, ttl time.Duration) (Lease, error)
}

A Semaphore provides an API for requesting ownership of an expirable semaphore.

Acquired semaphores have an expiration. If they're not released or kept alive during this period then they will expire and ownership of the semaphore will be lost.

TODO(edd): add AcquireTTL when needed. It should block.

var NopSemaphore Semaphore = nopSemaphore{}

NopSemaphore is a Semaphore that always hands out leases.

type Session ¶

type Session struct {
	// ID is only required for auditing purposes.
	ID          ID           `json:"id"`
	Key         string       `json:"key"`
	CreatedAt   time.Time    `json:"createdAt"`
	ExpiresAt   time.Time    `json:"expiresAt"`
	UserID      ID           `json:"userID,omitempty"`
	Permissions []Permission `json:"permissions,omitempty"`
}

Session is a user session.

func (*Session) EphemeralAuth ¶

func (s *Session) EphemeralAuth(orgID ID) *Authorization

EphemeralAuth generates an Authorization that is not stored but at the user's max privs.

func (*Session) Expired ¶

func (s *Session) Expired() error

Expired returns an error if the session is expired.

func (*Session) GetUserID ¶

func (s *Session) GetUserID() ID

GetUserID returns the user id.

func (*Session) Identifier ¶

func (s *Session) Identifier() ID

Identifier returns the sessions ID and is used for auditing.

func (*Session) Kind ¶

func (s *Session) Kind() string

Kind returns session and is used for auditing.

func (*Session) PermissionSet ¶

func (s *Session) PermissionSet() (PermissionSet, error)

PermissionSet returns the set of permissions associated with the session.

type SessionService ¶

type SessionService interface {
	FindSession(ctx context.Context, key string) (*Session, error)
	ExpireSession(ctx context.Context, key string) error
	CreateSession(ctx context.Context, user string) (*Session, error)
	// TODO: update RenewSession to take a ID instead of a session.
	// By taking a session object it could be confused to update more things about the session
	RenewSession(ctx context.Context, session *Session, newExpiration time.Time) error
}

SessionService represents a service for managing user sessions.

type SingleStatViewProperties ¶

type SingleStatViewProperties struct {
	Type              string           `json:"type"`
	Queries           []DashboardQuery `json:"queries"`
	Prefix            string           `json:"prefix"`
	TickPrefix        string           `json:"tickPrefix"`
	Suffix            string           `json:"suffix"`
	TickSuffix        string           `json:"tickSuffix"`
	ViewColors        []ViewColor      `json:"colors"`
	DecimalPlaces     DecimalPlaces    `json:"decimalPlaces"`
	Note              string           `json:"note"`
	ShowNoteWhenEmpty bool             `json:"showNoteWhenEmpty"`
}

SingleStatViewProperties represents options for single stat view in Chronograf

func (SingleStatViewProperties) GetType ¶

func (v SingleStatViewProperties) GetType() string

type Source ¶

type Source struct {
	ID                 ID         `json:"id,omitempty"`                 // ID is the unique ID of the source
	OrganizationID     ID         `json:"orgID"`                        // OrganizationID is the organization ID that resource belongs to
	Default            bool       `json:"default"`                      // Default specifies the default source for the application
	Name               string     `json:"name"`                         // Name is the user-defined name for the source
	Type               SourceType `json:"type,omitempty"`               // Type specifies which kinds of source (enterprise vs oss vs 2.0)
	URL                string     `json:"url"`                          // URL are the connections to the source
	InsecureSkipVerify bool       `json:"insecureSkipVerify,omitempty"` // InsecureSkipVerify as true means any certificate presented by the source is accepted
	Telegraf           string     `json:"telegraf"`                     // Telegraf is the db telegraf is written to.  By default it is "telegraf"
	SourceFields
	V1SourceFields
}

Source is an external Influx with time series data. TODO(desa): do we still need default? TODO(desa): do sources belong

type SourceFields ¶

type SourceFields struct {
	Token string `json:"token"` // Token is the 2.0 authorization token associated with a source
}

SourceFields is used to authorize against an influx 2.0 source.

type SourceQuery ¶

type SourceQuery struct {
	Query string `json:"query"`
	Type  string `json:"type"`
}

SourceQuery is a query for a source.

type SourceService ¶

type SourceService interface {
	// DefaultSource retrieves the default source.
	DefaultSource(ctx context.Context) (*Source, error)
	// FindSourceByID retrieves a source by its ID.
	FindSourceByID(ctx context.Context, id ID) (*Source, error)
	// FindSources returns a list of all sources.
	FindSources(ctx context.Context, opts FindOptions) ([]*Source, int, error)
	// CreateSource sets the sources ID and stores it.
	CreateSource(ctx context.Context, s *Source) error
	// UpdateSource updates the source.
	UpdateSource(ctx context.Context, id ID, upd SourceUpdate) (*Source, error)
	// DeleteSource removes the source.
	DeleteSource(ctx context.Context, id ID) error
}

SourceService is a service for managing sources.

type SourceType ¶

type SourceType string

SourceType is a string for types of sources.

type SourceUpdate ¶

type SourceUpdate struct {
	Name               *string     `json:"name"`
	Type               *SourceType `json:"type,omitempty"`
	Token              *string     `json:"token"`
	URL                *string     `json:"url"`
	InsecureSkipVerify *bool       `json:"insecureSkipVerify,omitempty"`
	Telegraf           *string     `json:"telegraf"`
	Username           *string     `json:"username,omitempty"`
	Password           *string     `json:"password,omitempty"`
	SharedSecret       *string     `json:"sharedSecret,omitempty"`
	MetaURL            *string     `json:"metaURL,omitempty"`
	Role               *string     `json:"role,omitempty"`
	DefaultRP          *string     `json:"defaultRP"`
}

SourceUpdate represents updates to a source.

func (SourceUpdate) Apply ¶

func (u SourceUpdate) Apply(s *Source) error

Apply applies an update to a source.

type Status ¶

type Status string

Status defines if a resource is active or inactive.

const (
	// Active status means that the resource can be used.
	Active Status = "active"
	// Inactive status means that the resource cannot be used.
	Inactive Status = "inactive"
)

func (Status) Ptr ¶

func (s Status) Ptr() *Status

Ptr returns the pointer of that status.

func (Status) Valid ¶

func (s Status) Valid() error

Valid determines if a Status value matches the enum.

type TableOptions ¶

type TableOptions struct {
	VerticalTimeAxis bool           `json:"verticalTimeAxis"`
	SortBy           RenamableField `json:"sortBy"`
	Wrapping         string         `json:"wrapping"`
	FixFirstColumn   bool           `json:"fixFirstColumn"`
}

TableOptions is a type of options for a DashboardView with type Table

type TableViewProperties ¶

type TableViewProperties struct {
	Type              string           `json:"type"`
	Queries           []DashboardQuery `json:"queries"`
	ViewColors        []ViewColor      `json:"colors"`
	TableOptions      TableOptions     `json:"tableOptions"`
	FieldOptions      []RenamableField `json:"fieldOptions"`
	TimeFormat        string           `json:"timeFormat"`
	DecimalPlaces     DecimalPlaces    `json:"decimalPlaces"`
	Note              string           `json:"note"`
	ShowNoteWhenEmpty bool             `json:"showNoteWhenEmpty"`
}

TableViewProperties represents options for table view in Chronograf

func (TableViewProperties) GetType ¶

func (v TableViewProperties) GetType() string

type Tag ¶

type Tag struct {
	Key   string `json:"key"`
	Value string `json:"value"`
}

Tag is a tag key-value pair.

func NewTag ¶

func NewTag(s string) (Tag, error)

NewTag generates a tag pair from a string in the format key:value.

func (*Tag) QueryParam ¶

func (t *Tag) QueryParam() string

QueryParam converts a Tag to a string query parameter

func (Tag) Valid ¶

func (t Tag) Valid() error

Valid returns an error if the tagpair is missing fields

type TagRule ¶

type TagRule struct {
	Tag
	Operator Operator `json:"operator"`
}

TagRule is the struct of tag rule.

func (TagRule) Valid ¶

func (tr TagRule) Valid() error

Valid returns error for invalid operators.

type Task ¶

type Task struct {
	ID              ID                     `json:"id"`
	Type            string                 `json:"type,omitempty"`
	OrganizationID  ID                     `json:"orgID"`
	Organization    string                 `json:"org"`
	OwnerID         ID                     `json:"ownerID"`
	Name            string                 `json:"name"`
	Description     string                 `json:"description,omitempty"`
	Status          string                 `json:"status"`
	Flux            string                 `json:"flux"`
	Every           string                 `json:"every,omitempty"`
	Cron            string                 `json:"cron,omitempty"`
	Offset          time.Duration          `json:"offset,omitempty"`
	LatestCompleted time.Time              `json:"latestCompleted,omitempty"`
	LatestScheduled time.Time              `json:"latestScheduled,omitempty"`
	LatestSuccess   time.Time              `json:"latestSuccess,omitempty"`
	LatestFailure   time.Time              `json:"latestFailure,omitempty"`
	LastRunStatus   string                 `json:"lastRunStatus,omitempty"`
	LastRunError    string                 `json:"lastRunError,omitempty"`
	CreatedAt       time.Time              `json:"createdAt,omitempty"`
	UpdatedAt       time.Time              `json:"updatedAt,omitempty"`
	Metadata        map[string]interface{} `json:"metadata,omitempty"`
}

Task is a task. 🎊

func (*Task) EffectiveCron ¶

func (t *Task) EffectiveCron() string

EffectiveCron returns the effective cron string of the options. If the cron option was specified, it is returned. If the every option was specified, it is converted into a cron string using "@every". Otherwise, the empty string is returned. The value of the offset option is not considered.

type TaskCreate ¶

type TaskCreate struct {
	Type           string                 `json:"type,omitempty"`
	Flux           string                 `json:"flux"`
	Description    string                 `json:"description,omitempty"`
	Status         string                 `json:"status,omitempty"`
	OrganizationID ID                     `json:"orgID,omitempty"`
	Organization   string                 `json:"org,omitempty"`
	OwnerID        ID                     `json:"-"`
	Metadata       map[string]interface{} `json:"-"` // not to be set through a web request but rather used by a http service using tasks backend.
}

TaskCreate is the set of values to create a task.

func (TaskCreate) Validate ¶

func (t TaskCreate) Validate() error

type TaskFilter ¶

type TaskFilter struct {
	Type           *string
	Name           *string
	After          *ID
	OrganizationID *ID
	Organization   string
	User           *ID
	Limit          int
	Status         *string
}

TaskFilter represents a set of filters that restrict the returned results

func (TaskFilter) QueryParams ¶

func (f TaskFilter) QueryParams() map[string][]string

QueryParams Converts TaskFilter fields to url query params.

type TaskService ¶

type TaskService interface {
	// FindTaskByID returns a single task
	FindTaskByID(ctx context.Context, id ID) (*Task, error)

	// FindTasks returns a list of tasks that match a filter (limit 100) and the total count
	// of matching tasks.
	FindTasks(ctx context.Context, filter TaskFilter) ([]*Task, int, error)

	// CreateTask creates a new task.
	// The owner of the task is inferred from the authorizer associated with ctx.
	CreateTask(ctx context.Context, t TaskCreate) (*Task, error)

	// UpdateTask updates a single task with changeset.
	UpdateTask(ctx context.Context, id ID, upd TaskUpdate) (*Task, error)

	// DeleteTask removes a task by ID and purges all associated data and scheduled runs.
	DeleteTask(ctx context.Context, id ID) error

	// FindLogs returns logs for a run.
	FindLogs(ctx context.Context, filter LogFilter) ([]*Log, int, error)

	// FindRuns returns a list of runs that match a filter and the total count of returned runs.
	FindRuns(ctx context.Context, filter RunFilter) ([]*Run, int, error)

	// FindRunByID returns a single run.
	FindRunByID(ctx context.Context, taskID, runID ID) (*Run, error)

	// CancelRun cancels a currently running run.
	CancelRun(ctx context.Context, taskID, runID ID) error

	// RetryRun creates and returns a new run (which is a retry of another run).
	RetryRun(ctx context.Context, taskID, runID ID) (*Run, error)

	// ForceRun forces a run to occur with unix timestamp scheduledFor, to be executed as soon as possible.
	// The value of scheduledFor may or may not align with the task's schedule.
	ForceRun(ctx context.Context, taskID ID, scheduledFor int64) (*Run, error)
}

TaskService represents a service for managing one-off and recurring tasks.

type TaskStatus ¶

type TaskStatus string
const (
	TaskActive   TaskStatus = "active"
	TaskInactive TaskStatus = "inactive"

	DefaultTaskStatus TaskStatus = TaskActive
)

type TaskUpdate ¶

type TaskUpdate struct {
	Flux        *string `json:"flux,omitempty"`
	Status      *string `json:"status,omitempty"`
	Description *string `json:"description,omitempty"`

	// LatestCompleted us to set latest completed on startup to skip task catchup
	LatestCompleted *time.Time             `json:"-"`
	LatestScheduled *time.Time             `json:"-"`
	LatestSuccess   *time.Time             `json:"-"`
	LatestFailure   *time.Time             `json:"-"`
	LastRunStatus   *string                `json:"-"`
	LastRunError    *string                `json:"-"`
	Metadata        map[string]interface{} `json:"-"` // not to be set through a web request but rather used by a http service using tasks backend.

	// Options gets unmarshalled from json as if it was flat, with the same level as Flux and Status.
	Options options.Options // when we unmarshal this gets unmarshalled from flat key-values
}

TaskUpdate represents updates to a task. Options updates override any options set in the Flux field.

func (*TaskUpdate) MarshalJSON ¶

func (t *TaskUpdate) MarshalJSON() ([]byte, error)

func (*TaskUpdate) UnmarshalJSON ¶

func (t *TaskUpdate) UnmarshalJSON(data []byte) error

func (*TaskUpdate) UpdateFlux ¶

func (t *TaskUpdate) UpdateFlux(parser FluxLanguageService, oldFlux string) error

UpdateFlux updates the TaskUpdate to go from updating options to updating a flux string, that now has those updated options in it. It zeros the options in the TaskUpdate.

func (*TaskUpdate) Validate ¶

func (t *TaskUpdate) Validate() error

type TelegrafConfig ¶

type TelegrafConfig struct {
	ID          ID                     `json:"id,omitempty"`          // ID of this config object.
	OrgID       ID                     `json:"orgID,omitempty"`       // OrgID is the id of the owning organization.
	Name        string                 `json:"name,omitempty"`        // Name of this config object.
	Description string                 `json:"description,omitempty"` // Decription of this config object.
	Config      string                 `json:"config,omitempty"`      // ConfigTOML contains the raw toml config.
	Metadata    map[string]interface{} `json:"metadata,omitempty"`    // Metadata for the config.
}

TelegrafConfig stores telegraf config for one telegraf instance.

func (*TelegrafConfig) CountPlugins ¶

func (tc *TelegrafConfig) CountPlugins() map[string]float64

CountPlugins returns a map of the number of times each plugin is used.

func (*TelegrafConfig) UnmarshalJSON ¶

func (tc *TelegrafConfig) UnmarshalJSON(b []byte) error

UnmarshalJSON implement the json.Unmarshaler interface. Gets called when reading from the kv db. mostly legacy so loading old/stored configs still work. May not remove for a while. Primarily will get hit when user views/downloads config.

type TelegrafConfigFilter ¶

type TelegrafConfigFilter struct {
	OrgID        *ID
	Organization *string
}

TelegrafConfigFilter represents a set of filter that restrict the returned telegraf configs.

type TelegrafConfigStore ¶

type TelegrafConfigStore interface {
	// FindTelegrafConfigByID returns a single telegraf config by ID.
	FindTelegrafConfigByID(ctx context.Context, id ID) (*TelegrafConfig, error)

	// FindTelegrafConfigs returns a list of telegraf configs that match filter and the total count of matching telegraf configs.
	// Additional options provide pagination & sorting.
	FindTelegrafConfigs(ctx context.Context, filter TelegrafConfigFilter, opt ...FindOptions) ([]*TelegrafConfig, int, error)

	// CreateTelegrafConfig creates a new telegraf config and sets b.ID with the new identifier.
	CreateTelegrafConfig(ctx context.Context, tc *TelegrafConfig, userID ID) error

	// UpdateTelegrafConfig updates a single telegraf config.
	// Returns the new telegraf config after update.
	UpdateTelegrafConfig(ctx context.Context, id ID, tc *TelegrafConfig, userID ID) (*TelegrafConfig, error)

	// DeleteTelegrafConfig removes a telegraf config by ID.
	DeleteTelegrafConfig(ctx context.Context, id ID) error
}

TelegrafConfigStore represents a service for managing telegraf config data.

type TenantService ¶

TenantService is a service that exposes the functionality of the embedded services.

type TimeGenerator ¶

type TimeGenerator interface {
	// Now creates the generated time.
	Now() time.Time
}

TimeGenerator represents a generator for now.

type Timespan ¶

type Timespan struct {
	Start time.Time `json:"start"`
	Stop  time.Time `json:"stop"`
}

Timespan represents a range of time.

type TokenGenerator ¶

type TokenGenerator interface {
	// Token generates a new API token.
	Token() (string, error)
}

TokenGenerator represents a generator for API tokens.

type Usage ¶

type Usage struct {
	OrganizationID *ID         `json:"organizationID,omitempty"`
	BucketID       *ID         `json:"bucketID,omitempty"`
	Type           UsageMetric `json:"type"`
	Value          float64     `json:"value"`
}

Usage is a metric associated with the utilization of a particular resource.

type UsageFilter ¶

type UsageFilter struct {
	OrgID    *ID
	BucketID *ID
	Range    *Timespan
}

UsageFilter is used to filter usage.

type UsageMetric ¶

type UsageMetric string

UsageMetric used to track classes of usage.

const (
	// UsageWriteRequestCount is the name of the metrics for tracking write request count.
	UsageWriteRequestCount UsageMetric = "usage_write_request_count"
	// UsageWriteRequestBytes is the name of the metrics for tracking the number of write bytes.
	UsageWriteRequestBytes UsageMetric = "usage_write_request_bytes"

	// UsageValues is the name of the metrics for tracking the number of values.
	UsageValues UsageMetric = "usage_values"
	// UsageSeries is the name of the metrics for tracking the number of series written.
	UsageSeries UsageMetric = "usage_series"

	// UsageQueryRequestCount is the name of the metrics for tracking query request count.
	UsageQueryRequestCount UsageMetric = "usage_query_request_count"
	// UsageQueryRequestBytes is the name of the metrics for tracking the number of query bytes.
	UsageQueryRequestBytes UsageMetric = "usage_query_request_bytes"
)

type UsageService ¶

type UsageService interface {
	GetUsage(ctx context.Context, filter UsageFilter) (map[UsageMetric]*Usage, error)
}

UsageService is a service for accessing usage statistics.

type User ¶

type User struct {
	ID      ID     `json:"id,omitempty"`
	Name    string `json:"name"`
	OAuthID string `json:"oauthID,omitempty"`
	Status  Status `json:"status"`
}

User is a user. 🎉

func (*User) Valid ¶

func (u *User) Valid() error

Valid validates user

type UserFilter ¶

type UserFilter struct {
	ID   *ID
	Name *string
}

UserFilter represents a set of filter that restrict the returned results.

type UserOperationLogService ¶

type UserOperationLogService interface {
	// GetUserOperationLog retrieves the operation log for the user with the provided id.
	GetUserOperationLog(ctx context.Context, id ID, opts FindOptions) ([]*OperationLogEntry, int, error)
}

UserOperationLogService is an interface for retrieving the operation log for a user.

type UserResourceMapping ¶

type UserResourceMapping struct {
	UserID       ID           `json:"userID"`
	UserType     UserType     `json:"userType"`
	MappingType  MappingType  `json:"mappingType"`
	ResourceType ResourceType `json:"resourceType"`
	ResourceID   ID           `json:"resourceID"`
}

UserResourceMapping represents a mapping of a resource to its user.

func (*UserResourceMapping) ToPermissions ¶

func (m *UserResourceMapping) ToPermissions() ([]Permission, error)

ToPermissions converts a user resource mapping into a set of permissions.

func (UserResourceMapping) Validate ¶

func (m UserResourceMapping) Validate() error

Validate reports any validation errors for the mapping.

type UserResourceMappingFilter ¶

type UserResourceMappingFilter struct {
	ResourceID   ID
	ResourceType ResourceType
	UserID       ID
	UserType     UserType
}

UserResourceMappingFilter represents a set of filters that restrict the returned results.

type UserResourceMappingService ¶

type UserResourceMappingService interface {
	// FindUserResourceMappings returns a list of UserResourceMappings that match filter and the total count of matching mappings.
	FindUserResourceMappings(ctx context.Context, filter UserResourceMappingFilter, opt ...FindOptions) ([]*UserResourceMapping, int, error)

	// CreateUserResourceMapping creates a user resource mapping.
	CreateUserResourceMapping(ctx context.Context, m *UserResourceMapping) error

	// DeleteUserResourceMapping deletes a user resource mapping.
	DeleteUserResourceMapping(ctx context.Context, resourceID, userID ID) error
}

UserResourceMappingService maps the relationships between users and resources.

type UserService ¶

type UserService interface {

	// Returns a single user by ID.
	FindUserByID(ctx context.Context, id ID) (*User, error)

	// Returns the first user that matches filter.
	FindUser(ctx context.Context, filter UserFilter) (*User, error)

	// Returns a list of users that match filter and the total count of matching users.
	// Additional options provide pagination & sorting.
	FindUsers(ctx context.Context, filter UserFilter, opt ...FindOptions) ([]*User, int, error)

	// Creates a new user and sets u.ID with the new identifier.
	CreateUser(ctx context.Context, u *User) error

	// Updates a single user with changeset.
	// Returns the new user state after update.
	UpdateUser(ctx context.Context, id ID, upd UserUpdate) (*User, error)

	// Removes a user by ID.
	DeleteUser(ctx context.Context, id ID) error

	// FindPermissionForUser
	FindPermissionForUser(ctx context.Context, UserID ID) (PermissionSet, error)
}

UserService represents a service for managing user data.

type UserStatus ¶

type UserStatus string

UserStatus indicates whether a user is active or inactive

func (*UserStatus) Valid ¶

func (u *UserStatus) Valid() error

Valid validates user status

type UserType ¶

type UserType string

UserType can either be owner or member.

const (
	// Owner can read and write to a resource
	Owner UserType = "owner" // 1
	// Member can read from a resource.
	Member UserType = "member" // 2
)

func (UserType) Valid ¶

func (ut UserType) Valid() (err error)

Valid checks if the UserType is a member of the UserType enum

type UserUpdate ¶

type UserUpdate struct {
	Name   *string `json:"name"`
	Status *Status `json:"status"`
}

UserUpdate represents updates to a user. Only fields which are set are updated.

func (UserUpdate) Valid ¶

func (uu UserUpdate) Valid() error

Valid validates UserUpdate

type V1SourceFields ¶

type V1SourceFields struct {
	Username     string `json:"username,omitempty"`     // Username is the username to connect to the source
	Password     string `json:"password,omitempty"`     // Password is in CLEARTEXT
	SharedSecret string `json:"sharedSecret,omitempty"` // ShareSecret is the optional signing secret for Influx JWT authorization
	MetaURL      string `json:"metaUrl,omitempty"`      // MetaURL is the url for the meta node
	DefaultRP    string `json:"defaultRP"`              // DefaultRP is the default retention policy used in database queries to this source
}

V1SourceFields are the fields for connecting to a 1.0 source (oss or enterprise)

type Variable ¶

type Variable struct {
	ID             ID                 `json:"id,omitempty"`
	OrganizationID ID                 `json:"orgID,omitempty"`
	Name           string             `json:"name"`
	Description    string             `json:"description"`
	Selected       []string           `json:"selected"`
	Arguments      *VariableArguments `json:"arguments"`
	CRUDLog
}

A Variable describes a keyword that can be expanded into several possible values when used in an InfluxQL or Flux query

func (*Variable) Valid ¶

func (m *Variable) Valid() error

Valid returns an error if a Variable contains invalid data

type VariableArguments ¶

type VariableArguments struct {
	Type   string      `json:"type"`   // "constant", "map", or "query"
	Values interface{} `json:"values"` // either VariableQueryValues, VariableConstantValues, VariableMapValues
}

A VariableArguments contains arguments used when expanding a Variable

func (*VariableArguments) UnmarshalJSON ¶

func (a *VariableArguments) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshals json into a VariableArguments struct, using the `Type` field to assign the approriate struct to the `Values` field

type VariableConstantValues ¶

type VariableConstantValues []string

VariableConstantValues are the data for expanding a constants-based Variable

type VariableFilter ¶

type VariableFilter struct {
	ID             *ID
	OrganizationID *ID
	Organization   *string
}

VariableFilter represents a set of filter that restrict the returned results.

func (VariableFilter) QueryParams ¶

func (f VariableFilter) QueryParams() map[string][]string

QueryParams implements PagingFilter.

It converts VariableFilter fields to url query params.

type VariableMapValues ¶

type VariableMapValues map[string]string

VariableMapValues are the data for expanding a map-based Variable

type VariableQueryValues ¶

type VariableQueryValues struct {
	Query    string `json:"query"`
	Language string `json:"language"` // "influxql" or "flux"
}

VariableQueryValues contains a query used when expanding a query-based Variable

type VariableService ¶

type VariableService interface {
	// FindVariableByID finds a single variable from the store by its ID
	FindVariableByID(ctx context.Context, id ID) (*Variable, error)

	// FindVariables returns all variables in the store
	FindVariables(ctx context.Context, filter VariableFilter, opt ...FindOptions) ([]*Variable, error)

	// CreateVariable creates a new variable and assigns it an ID
	CreateVariable(ctx context.Context, m *Variable) error

	// UpdateVariable updates a single variable with a changeset
	UpdateVariable(ctx context.Context, id ID, update *VariableUpdate) (*Variable, error)

	// ReplaceVariable replaces a single variable
	ReplaceVariable(ctx context.Context, variable *Variable) error

	// DeleteVariable removes a variable from the store
	DeleteVariable(ctx context.Context, id ID) error
}

VariableService describes a service for managing Variables

type VariableUpdate ¶

type VariableUpdate struct {
	Name        string             `json:"name"`
	Selected    []string           `json:"selected"`
	Description string             `json:"description"`
	Arguments   *VariableArguments `json:"arguments"`
}

A VariableUpdate describes a set of changes that can be applied to a Variable

func (*VariableUpdate) Apply ¶

func (u *VariableUpdate) Apply(m *Variable)

Apply applies non-zero fields from a VariableUpdate to a Variable

func (*VariableUpdate) Valid ¶

func (u *VariableUpdate) Valid() error

Valid returns an error if a Variable changeset is not valid

type View ¶

type View struct {
	ViewContents
	Properties ViewProperties
}

View holds positional and visual information for a View.

func (View) MarshalJSON ¶

func (v View) MarshalJSON() ([]byte, error)

MarshalJSON encodes a view to JSON bytes.

func (*View) UnmarshalJSON ¶

func (c *View) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes JSON bytes into the corresponding view type (those that implement ViewProperties).

type ViewColor ¶

type ViewColor struct {
	ID    string  `json:"id"`    // ID is the unique id of the View color
	Type  string  `json:"type"`  // Type is how the color is used. Accepted (min,max,threshold)
	Hex   string  `json:"hex"`   // Hex is the hex number of the color
	Name  string  `json:"name"`  // Name is the user-facing name of the hex color
	Value float64 `json:"value"` // Value is the data value mapped to this color
}

ViewColor represents the encoding of data into visualizations

type ViewContents ¶

type ViewContents struct {
	ID   ID     `json:"id,omitempty"`
	Name string `json:"name"`
}

ViewContents is the id and name of a specific view.

type ViewContentsUpdate ¶

type ViewContentsUpdate struct {
	Name *string `json:"name"`
}

ViewContentsUpdate is a struct for updating the non properties content of a View.

type ViewFilter ¶

type ViewFilter struct {
	ID    *ID
	Types []string
}

ViewFilter represents a set of filter that restrict the returned results.

type ViewProperties ¶

type ViewProperties interface {
	GetType() string
	// contains filtered or unexported methods
}

ViewProperties is used to mark other structures as conforming to a View.

func UnmarshalViewPropertiesJSON ¶

func UnmarshalViewPropertiesJSON(b []byte) (ViewProperties, error)

UnmarshalViewPropertiesJSON unmarshals JSON bytes into a ViewProperties.

type ViewUpdate ¶

type ViewUpdate struct {
	ViewContentsUpdate
	Properties ViewProperties
}

ViewUpdate is a struct for updating Views.

func (ViewUpdate) Apply ¶

func (u ViewUpdate) Apply(v *View) error

Apply updates a view with the view updates properties.

func (ViewUpdate) MarshalJSON ¶

func (u ViewUpdate) MarshalJSON() ([]byte, error)

MarshalJSON encodes a view to JSON bytes.

func (*ViewUpdate) UnmarshalJSON ¶

func (u *ViewUpdate) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes JSON bytes into the corresponding view update type (those that implement ViewProperties).

func (ViewUpdate) Valid ¶

func (u ViewUpdate) Valid() *Error

Valid validates the update struct. It expects minimal values to be set.

type WriteService ¶

type WriteService interface {
	WriteTo(ctx context.Context, filter BucketFilter, r io.Reader) error
}

WriteService writes data read from the reader.

type XYViewProperties ¶

type XYViewProperties struct {
	Queries                    []DashboardQuery `json:"queries"`
	Axes                       map[string]Axis  `json:"axes"`
	Type                       string           `json:"type"`
	Legend                     Legend           `json:"legend"`
	Geom                       string           `json:"geom"` // Either "line", "step", "stacked", or "bar"
	ViewColors                 []ViewColor      `json:"colors"`
	Note                       string           `json:"note"`
	ShowNoteWhenEmpty          bool             `json:"showNoteWhenEmpty"`
	XColumn                    string           `json:"xColumn"`
	GenerateXAxisTicks         []string         `json:"generateXAxisTicks"`
	XTotalTicks                int              `json:"xTotalTicks"`
	XTickStart                 float64          `json:"xTickStart"`
	XTickStep                  float64          `json:"xTickStep"`
	YColumn                    string           `json:"yColumn"`
	GenerateYAxisTicks         []string         `json:"generateYAxisTicks"`
	YTotalTicks                int              `json:"yTotalTicks"`
	YTickStart                 float64          `json:"yTickStart"`
	YTickStep                  float64          `json:"yTickStep"`
	ShadeBelow                 bool             `json:"shadeBelow"`
	Position                   string           `json:"position"`
	TimeFormat                 string           `json:"timeFormat"`
	HoverDimension             string           `json:"hoverDimension"`
	LegendColorizeRows         bool             `json:"legendColorizeRows"`
	LegendOpacity              float64          `json:"legendOpacity"`
	LegendOrientationThreshold int              `json:"legendOrientationThreshold"`
}

XYViewProperties represents options for line, bar, step, or stacked view in Chronograf

func (XYViewProperties) GetType ¶

func (v XYViewProperties) GetType() string

Directories ¶

Path Synopsis
cmd
influx_inspect/verify/tombstone
Package tombstone verifies integrity of tombstones.
Package tombstone verifies integrity of tombstones.
influx_inspect/verify/tsm
Package tsm verifies integrity of TSM files.
Package tsm verifies integrity of TSM files.
mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
This package imports all the influxdb-specific query builtins.
This package imports all the influxdb-specific query builtins.
static
The fluxinit/static package can be imported in test cases and other uses cases where it is okay to always initialize flux.
The fluxinit/static package can be imported in test cases and other uses cases where it is okay to always initialize flux.
mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
query/mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
query/neldermead
Package neldermead is an implementation of the Nelder-Mead optimization method.
Package neldermead is an implementation of the Nelder-Mead optimization method.
fs
kit
check
Package check standardizes /health and /ready endpoints.
Package check standardizes /health and /ready endpoints.
cli
Package cli creates simple CLI options with ENV overrides using viper.
Package cli creates simple CLI options with ENV overrides using viper.
feature
Package feature provides feature flagging capabilities for InfluxDB servers.
Package feature provides feature flagging capabilities for InfluxDB servers.
io
prom
Package prom provides a wrapper around a prometheus metrics registry so that all services are unified in how they expose prometheus metrics.
Package prom provides a wrapper around a prometheus metrics registry so that all services are unified in how they expose prometheus metrics.
prom/promtest
Package promtest provides helpers for parsing and extracting prometheus metrics.
Package promtest provides helpers for parsing and extracting prometheus metrics.
kv
package kv The KV package is a set of services and abstractions built around key value storage.
package kv The KV package is a set of services and abstractions built around key value storage.
migration
package migration This package contains utility types for composing and running schema and data migrations in a strictly serial and ordered nature; against a backing kv.SchemaStore implementation.
package migration This package contains utility types for composing and running schema and data migrations in a strictly serial and ordered nature; against a backing kv.SchemaStore implementation.
migration/all
package all This package is the canonical location for all migrations being made against the single shared kv.Store implementation used by InfluxDB (while it remains a single store).
package all This package is the canonical location for all migrations being made against the single shared kv.Store implementation used by InfluxDB (while it remains a single store).
mock
Package mock is a generated GoMock package.
Package mock is a generated GoMock package.
Package mock is a generated GoMock package.
Package mock is a generated GoMock package.
Package models implements basic objects used throughout the TICK stack.
Package models implements basic objects used throughout the TICK stack.
pkg
deep
Package deep provides a deep equality check for use in tests.
Package deep provides a deep equality check for use in tests.
encoding/simple8b
Package simple8b implements the 64bit integer encoding algorithm as published by Ann and Moffat in "Index compression using 64-bit words", Softw.
Package simple8b implements the 64bit integer encoding algorithm as published by Ann and Moffat in "Index compression using 64-bit words", Softw.
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.
estimator/hll
Package hll contains a HyperLogLog++ with a LogLog-Beta bias correction implementation that is adapted (mostly copied) from an implementation provided by Clark DuVall github.com/clarkduvall/hyperloglog.
Package hll contains a HyperLogLog++ with a LogLog-Beta bias correction implementation that is adapted (mostly copied) from an implementation provided by Clark DuVall github.com/clarkduvall/hyperloglog.
fs
limiter
Package limiter provides concurrency limiters.
Package limiter provides concurrency limiters.
metrics
Package metrics provides various measurements that are safe for concurrent access.
Package metrics provides various measurements that are safe for concurrent access.
mmap
Package mmap provides a way to memory-map a file.
Package mmap provides a way to memory-map a file.
pointer
Package pointer provides utilities for pointer handling that aren't available in go.
Package pointer provides utilities for pointer handling that aren't available in go.
pool
Package pool provides pool structures to help reduce garbage collector pressure.
Package pool provides pool structures to help reduce garbage collector pressure.
rhh
slices
Package slices contains functions to operate on slices treated as sets.
Package slices contains functions to operate on slices treated as sets.
tar
testing/assert
Package assert provides helper functions that can be used with the standard Go testing package.
Package assert provides helper functions that can be used with the standard Go testing package.
tracing
Package tracing provides a way for capturing hierarchical traces.
Package tracing provides a way for capturing hierarchical traces.
tracing/wire
Package wire is used to serialize a trace.
Package wire is used to serialize a trace.
Package pkger implements a means to create and consume reusable templates for what will eventually come to support all influxdb resources.
Package pkger implements a means to create and consume reusable templates for what will eventually come to support all influxdb resources.
control
Package control keeps track of resources and manages queries.
Package control keeps track of resources and manages queries.
fluxlang
Package language exposes the flux parser as an interface.
Package language exposes the flux parser as an interface.
influxql
Package influxql implements the transpiler for executing influxql queries in the 2.0 query engine.
Package influxql implements the transpiler for executing influxql queries in the 2.0 query engine.
influxql/spectests
Package spectests the influxql transpiler specification tests.
Package spectests the influxql transpiler specification tests.
Package resource defines an interface for recording changes to InfluxDB resources.
Package resource defines an interface for recording changes to InfluxDB resources.
mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
task
backend/executor/mock
Package mock is a generated GoMock package.
Package mock is a generated GoMock package.
mock
Package mock contains mock implementations of different task interfaces.
Package mock contains mock implementations of different task interfaces.
options
Package options provides ways to extract the task-related options from a Flux script.
Package options provides ways to extract the task-related options from a Flux script.
servicetest
Package servicetest provides tests to ensure that implementations of platform/task/backend.Store and platform/task/backend.LogReader meet the requirements of influxdb.TaskService.
Package servicetest provides tests to ensure that implementations of platform/task/backend.Store and platform/task/backend.LogReader meet the requirements of influxdb.TaskService.
The tenant domain encapsulates all the storage critical metadata services: User Organization Bucket URM's These services are the cornerstone of all other metadata services.
The tenant domain encapsulates all the storage critical metadata services: User Organization Bucket URM's These services are the cornerstone of all other metadata services.
Package tests contains a set of integration tests, which run in-memory versions of various 2.0 services.
Package tests contains a set of integration tests, which run in-memory versions of various 2.0 services.
Package toml adds support to marshal and unmarshal types not in the official TOML spec.
Package toml adds support to marshal and unmarshal types not in the official TOML spec.
tools
cursors/mock
Package mock is a generated GoMock package.
Package mock is a generated GoMock package.
engine
Package engine can be imported to initialize and register all available TSDB engines.
Package engine can be imported to initialize and register all available TSDB engines.
engine/tsm1
Package tsm1 provides a TSDB in the Time Structured Merge tree format.
Package tsm1 provides a TSDB in the Time Structured Merge tree format.
index/tsi1
Package tsi1 provides a memory-mapped index implementation that supports high cardinality series.
Package tsi1 provides a memory-mapped index implementation that supports high cardinality series.
Package uuid provides functions to create time-based UUIDs.
Package uuid provides functions to create time-based UUIDs.
v1
authorization/mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
coordinator
Package coordinator contains abstractions for writing points, executing statements, and accessing meta data.
Package coordinator contains abstractions for writing points, executing statements, and accessing meta data.
monitor
Package monitor provides a service and associated functionality for InfluxDB to self-monitor internal statistics and diagnostics.
Package monitor provides a service and associated functionality for InfluxDB to self-monitor internal statistics and diagnostics.
monitor/diagnostics
Package diagnostics provides the diagnostics type so that other packages can provide diagnostics without depending on the monitor package.
Package diagnostics provides the diagnostics type so that other packages can provide diagnostics without depending on the monitor package.
services/meta
Package meta provides control over meta data for InfluxDB, such as controlling databases, retention policies, users, etc.
Package meta provides control over meta data for InfluxDB, such as controlling databases, retention policies, users, etc.
services/precreator
Package precreator provides the shard precreation service.
Package precreator provides the shard precreation service.
services/retention
Package retention provides the retention policy enforcement service.
Package retention provides the retention policy enforcement service.

Jump to

Keyboard shortcuts

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