http

package
v2.7.6 Latest Latest
Warning

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

Go to latest
Published: Apr 12, 2024 License: MIT Imports: 77 Imported by: 1

README

HTTP Handler Style Guide

HTTP Handler
  • Each handler should implement http.Handler
    • This can be done by embedding a httprouter.Router (a light weight HTTP router that supports variables in the routing pattern and matches against the request method)
  • Required services should be exported on the struct
// ThingHandler represents an HTTP API handler for things.
type ThingHandler struct {
	// embedded httprouter.Router as a lazy way to implement http.Handler
	*httprouter.Router

	ThingService         platform.ThingService
	AuthorizationService platform.AuthorizationService

	Logger               *zap.Logger
}
HTTP Handler Constructor
  • Routes should be declared in the constructor
// NewThingHandler returns a new instance of ThingHandler.
func NewThingHandler() *ThingHandler {
	h := &ThingHandler{
		Router: httprouter.New(),
		Logger: zap.Nop(),
	}

	h.HandlerFunc("POST", "/api/v2/things", h.handlePostThing)
	h.HandlerFunc("GET", "/api/v2/things", h.handleGetThings)

	return h
}
Route handlers (http.HandlerFuncs)
  • Each route handler should have an associated request struct and decode function
  • The decode function should take a context.Context and an *http.Request and return the associated route request struct
type postThingRequest struct {
	Thing *platform.Thing
}

func decodePostThingRequest(ctx context.Context, r *http.Request) (*postThingRequest, error) {
	t := &platform.Thing{}
	if err := json.NewDecoder(r.Body).Decode(t); err != nil {
		return nil, err
	}

	return &postThingRequest{
		Thing: t,
	}, nil
}
  • Route http.HandlerFuncs should separate the decoding and encoding of HTTP requests/response from actual handler logic
// handlePostThing is the HTTP handler for the POST /api/v2/things route.
func (h *ThingHandler) handlePostThing(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	req, err := decodePostThingRequest(ctx, r)
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}

	// Do stuff here
	if err := h.ThingService.CreateThing(ctx, req.Thing); err != nil {
		EncodeError(ctx, err, w)
		return
	}

	if err := encodeResponse(ctx, w, http.StatusCreated, req.Thing); err != nil {
		h.Logger.Info("encoding response failed", zap.Error(err))
		return
	}
}
  • http.HandlerFunc's that require particular encoding of http responses should implement an encode response function

Documentation

Index

Constants

View Source
const (
	// MetricsPath exposes the prometheus metrics over /metrics.
	MetricsPath = "/metrics"
	// ReadyPath exposes the readiness of the service over /ready.
	ReadyPath = "/ready"
	// HealthPath exposes the health of the service over /health.
	HealthPath = "/health"
	// DebugPath exposes /debug/pprof for go debugging.
	DebugPath = "/debug"
)
View Source
const (
	// OrgID is the http query parameter to specify an organization by ID.
	OrgID = "orgID"
	// Org is the http query parameter that take either the ID or Name interchangeably
	Org = "org"
	// BucketID is the http query parameter to specify an bucket by ID.
	BucketID = "bucketID"
	// Bucket is the http query parameter take either the ID or Name interchangably
	Bucket = "bucket"
)

Variables

View Source
var (
	ErrAuthHeaderMissing = errors.New("authorization Header is missing")
	ErrAuthBadScheme     = errors.New("authorization Header Scheme is invalid")
)

errors

DefaultTransport wraps http.DefaultTransport in SpanTransport to inject tracing headers into all outgoing requests.

View Source
var DefaultTransportInsecure http.RoundTripper = &SpanTransport{
	base: &http.Transport{
		Proxy: http.ProxyFromEnvironment,
		DialContext: (&net.Dialer{
			Timeout:   30 * time.Second,
			KeepAlive: 30 * time.Second,
			DualStack: true,
		}).DialContext,
		ForceAttemptHTTP2:     true,
		MaxIdleConns:          100,
		IdleConnTimeout:       90 * time.Second,
		TLSHandshakeTimeout:   10 * time.Second,
		ExpectContinueTimeout: 1 * time.Second,
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify: true,
		},
	},
}

DefaultTransportInsecure is identical to DefaultTransport, with the exception that tls.Config is configured with InsecureSkipVerify set to true.

View Source
var ErrInvalidDuration = &errors.Error{
	Code: errors.EInvalid,
	Msg:  "invalid duration",
}

ErrInvalidDuration is returned when parsing a malformatted duration.

Functions

func CheckError

func CheckError(resp *http.Response) (err error)

CheckError reads the http.Response and returns an error if one exists. It will automatically recognize the errors returned by Influx services and decode the error into an internal error type. If the error cannot be determined in that way, it will create a generic error message.

If there is no error, then this returns nil.

func CheckErrorStatus

func CheckErrorStatus(code int, res *http.Response) error

CheckErrorStatus for status and any error in the response.

func Debug added in v2.7.0

func Debug(ctx context.Context, next http.Handler, f Flusher, service influxdb.OnboardingService) http.HandlerFunc

func FormatDuration

func FormatDuration(d time.Duration) string

FormatDuration formats a duration to a string.

func GetQueryResponse

func GetQueryResponse(qr *QueryRequest, addr *url.URL, org, token string, headers ...string) (*http.Response, error)

GetQueryResponse runs a flux query with common parameters and returns the response from the query service.

func GetQueryResponseBody

func GetQueryResponseBody(res *http.Response) ([]byte, error)

GetQueryResponseBody reads the body of a response from some query service. It also checks for errors in the response.

func GetToken

func GetToken(r *http.Request) (string, error)

GetToken will parse the token from http Authorization Header.

func HealthHandler

func HealthHandler(w http.ResponseWriter, r *http.Request)

HealthHandler returns the status of the process.

func InactiveUserError

func InactiveUserError(ctx context.Context, h errors.HTTPErrorHandler, w http.ResponseWriter)

InactiveUserError encode a error message and status code for inactive users.

func LoggingMW

func LoggingMW(log *zap.Logger) kithttp.Middleware

LoggingMW middleware for logging inflight http requests.

func NewBaseChiRouter

func NewBaseChiRouter(api *kithttp.API) chi.Router

NewBaseChiRouter returns a new chi router with a 404 handler, a 405 handler, and a panic handler.

func NewBucketResponse

func NewBucketResponse(b *influxdb.Bucket, labels []*influxdb.Label) *bucketResponse

func NewClient

func NewClient(scheme string, insecure bool) *http.Client

NewClient returns an http.Client that pools connections and injects a span.

func NewHTTPClient

func NewHTTPClient(addr, token string, insecureSkipVerify bool, opts ...httpc.ClientOptFn) (*httpc.Client, error)

NewHTTPClient creates a new httpc.Client type. This call sets all the options that are important to the http pkg on the httpc client. The default status fn and so forth will all be set for the caller. In addition, some options can be specified. Those will be added to the defaults.

func NewResourceListHandler added in v2.0.9

func NewResourceListHandler() http.Handler

NewResourceListHandler is the HTTP handler for the GET /api/v2/resources route.

func NewRouter

NewRouter returns a new router with a 404 handler, a 405 handler, and a panic handler.

func NewURL

func NewURL(addr, path string) (*url.URL, error)

NewURL concats addr and path.

func ParseDuration

func ParseDuration(s string) (time.Duration, error)

ParseDuration parses a time duration from a string. This is needed instead of time.ParseDuration because this will support the full syntax that InfluxQL supports for specifying durations including weeks and days.

func ProbeAuthScheme

func ProbeAuthScheme(r *http.Request) (string, error)

ProbeAuthScheme probes the http request for the requests for token or cookie session.

func QueryHealthCheck

func QueryHealthCheck(url string, insecureSkipVerify bool) check.Response

func ReadyHandler

func ReadyHandler() http.Handler

ReadyHandler is a default readiness handler. The default behaviour is always ready.

func Redoc

func Redoc(swagger string) http.HandlerFunc

Redoc servers the swagger JSON using the redoc package.

func SetToken

func SetToken(token string, req *http.Request)

SetToken adds the token to the request.

func SimpleQuery

func SimpleQuery(addr *url.URL, flux, org, token string, headers ...string) ([]byte, error)

SimpleQuery runs a flux query with common parameters and returns CSV results.

func UnauthorizedError

func UnauthorizedError(ctx context.Context, h errors.HTTPErrorHandler, w http.ResponseWriter)

UnauthorizedError encodes a error message and status code for unauthorized access.

Types

type APIBackend

type APIBackend struct {
	AssetsPath     string // if empty then assets are served from bindata.
	UIDisabled     bool   // if true requests for the UI will return 404
	Logger         *zap.Logger
	FluxLogEnabled bool
	errors.HTTPErrorHandler
	SessionRenewDisabled bool
	// MaxBatchSizeBytes is the maximum number of bytes which can be written
	// in a single points batch
	MaxBatchSizeBytes int64

	// WriteParserMaxBytes specifies the maximum number of bytes that may be allocated when processing a single
	// write request. A value of zero specifies there is no limit.
	WriteParserMaxBytes int

	// WriteParserMaxLines specifies the maximum number of lines that may be parsed when processing a single
	// write request. A value of zero specifies there is no limit.
	WriteParserMaxLines int

	// WriteParserMaxValues specifies the maximum number of values that may be parsed when processing a single
	// write request. A value of zero specifies there is no limit.
	WriteParserMaxValues int

	NewQueryService func(*influxdb.Source) (query.ProxyQueryService, error)

	WriteEventRecorder metric.EventRecorder
	QueryEventRecorder metric.EventRecorder

	AlgoWProxy FeatureProxyHandler

	PointsWriter                    storage.PointsWriter
	DeleteService                   influxdb.DeleteService
	BackupService                   influxdb.BackupService
	SqlBackupRestoreService         influxdb.SqlBackupRestoreService
	BucketManifestWriter            influxdb.BucketManifestWriter
	RestoreService                  influxdb.RestoreService
	AuthorizationService            influxdb.AuthorizationService
	AuthorizationV1Service          influxdb.AuthorizationService
	PasswordV1Service               influxdb.PasswordsService
	AuthorizerV1                    influxdb.AuthorizerV1
	OnboardingService               influxdb.OnboardingService
	DBRPService                     influxdb.DBRPMappingService
	BucketService                   influxdb.BucketService
	SessionService                  influxdb.SessionService
	UserService                     influxdb.UserService
	OrganizationService             influxdb.OrganizationService
	UserResourceMappingService      influxdb.UserResourceMappingService
	LabelService                    influxdb.LabelService
	DashboardService                influxdb.DashboardService
	DashboardOperationLogService    influxdb.DashboardOperationLogService
	BucketOperationLogService       influxdb.BucketOperationLogService
	UserOperationLogService         influxdb.UserOperationLogService
	OrganizationOperationLogService influxdb.OrganizationOperationLogService
	SourceService                   influxdb.SourceService
	VariableService                 influxdb.VariableService
	PasswordsService                influxdb.PasswordsService
	InfluxqldService                influxql.ProxyQueryService
	FluxService                     query.ProxyQueryService
	FluxLanguageService             fluxlang.FluxLanguageService
	TaskService                     taskmodel.TaskService
	CheckService                    influxdb.CheckService
	TelegrafService                 influxdb.TelegrafConfigStore
	ScraperTargetStoreService       influxdb.ScraperTargetStoreService
	SecretService                   influxdb.SecretService
	LookupService                   influxdb.LookupService
	OrgLookupService                authorizer.OrgIDResolver
	DocumentService                 influxdb.DocumentService
	NotificationRuleStore           influxdb.NotificationRuleStore
	NotificationEndpointService     influxdb.NotificationEndpointService
	Flagger                         feature.Flagger
	FlagsHandler                    http.Handler
}

APIBackend is all services and associated parameters required to construct an APIHandler.

func (*APIBackend) PrometheusCollectors

func (b *APIBackend) PrometheusCollectors() []prometheus.Collector

PrometheusCollectors exposes the prometheus collectors associated with an APIBackend.

type APIHandler

type APIHandler struct {
	chi.Router
}

APIHandler is a collection of all the service handlers.

func NewAPIHandler

func NewAPIHandler(b *APIBackend, opts ...APIHandlerOptFn) *APIHandler

NewAPIHandler constructs all api handlers beneath it and returns an APIHandler

type APIHandlerOptFn

type APIHandlerOptFn func(chi.Router)

APIHandlerOptFn is a functional input param to set parameters on the APIHandler.

func WithResourceHandler

func WithResourceHandler(resHandler kithttp.ResourceHandler) APIHandlerOptFn

WithResourceHandler registers a resource handler on the APIHandler.

type AddHeader added in v2.0.9

type AddHeader struct {
	WriteHeader func(header http.Header)
}

func (*AddHeader) Middleware added in v2.0.9

func (h *AddHeader) Middleware(next http.Handler) http.Handler

Middleware is a middleware that mutates the header of all responses

type AuthenticationHandler

type AuthenticationHandler struct {
	errors2.HTTPErrorHandler

	AuthorizationService platform.AuthorizationService
	SessionService       platform.SessionService
	UserService          platform.UserService
	TokenParser          *jsonweb.TokenParser
	SessionRenewDisabled bool

	Handler http.Handler
	// contains filtered or unexported fields
}

AuthenticationHandler is a middleware for authenticating incoming requests.

func NewAuthenticationHandler

func NewAuthenticationHandler(log *zap.Logger, h errors2.HTTPErrorHandler) *AuthenticationHandler

NewAuthenticationHandler creates an authentication handler.

func (*AuthenticationHandler) RegisterNoAuthRoute

func (h *AuthenticationHandler) RegisterNoAuthRoute(method, path string)

RegisterNoAuthRoute excludes routes from needing authentication.

func (*AuthenticationHandler) ServeHTTP

ServeHTTP extracts the session or token from the http request and places the resulting authorizer on the request context.

type AuthorizationBackend

type AuthorizationBackend struct {
	errors2.HTTPErrorHandler

	AuthorizationService influxdb.AuthorizationService
	OrganizationService  influxdb.OrganizationService
	UserService          influxdb.UserService
	LookupService        influxdb.LookupService
	// contains filtered or unexported fields
}

AuthorizationBackend is all services and associated parameters required to construct the AuthorizationHandler.

func NewAuthorizationBackend

func NewAuthorizationBackend(log *zap.Logger, b *APIBackend) *AuthorizationBackend

NewAuthorizationBackend returns a new instance of AuthorizationBackend.

type AuthorizationHandler

type AuthorizationHandler struct {
	*httprouter.Router
	errors2.HTTPErrorHandler

	OrganizationService  influxdb.OrganizationService
	UserService          influxdb.UserService
	AuthorizationService influxdb.AuthorizationService
	LookupService        influxdb.LookupService
	// contains filtered or unexported fields
}

AuthorizationHandler represents an HTTP API handler for authorizations.

func NewAuthorizationHandler

func NewAuthorizationHandler(log *zap.Logger, b *AuthorizationBackend) *AuthorizationHandler

NewAuthorizationHandler returns a new instance of AuthorizationHandler.

type AuthorizationService

type AuthorizationService struct {
	Client *httpc.Client
}

AuthorizationService connects to Influx via HTTP using tokens to manage authorizations

func (*AuthorizationService) CreateAuthorization

func (s *AuthorizationService) CreateAuthorization(ctx context.Context, a *influxdb.Authorization) error

CreateAuthorization creates a new authorization and sets b.ID with the new identifier.

func (*AuthorizationService) DeleteAuthorization

func (s *AuthorizationService) DeleteAuthorization(ctx context.Context, id platform.ID) error

DeleteAuthorization removes a authorization by id.

func (*AuthorizationService) FindAuthorizationByID

func (s *AuthorizationService) FindAuthorizationByID(ctx context.Context, id platform.ID) (*influxdb.Authorization, error)

FindAuthorizationByID finds the authorization against a remote influx server.

func (*AuthorizationService) FindAuthorizationByToken

func (s *AuthorizationService) FindAuthorizationByToken(ctx context.Context, token string) (*influxdb.Authorization, error)

FindAuthorizationByToken returns a single authorization by Token.

func (*AuthorizationService) FindAuthorizations

func (s *AuthorizationService) FindAuthorizations(ctx context.Context, filter influxdb.AuthorizationFilter, opt ...influxdb.FindOptions) ([]*influxdb.Authorization, int, error)

FindAuthorizations returns a list of authorizations that match filter and the total count of matching authorizations. Additional options provide pagination & sorting.

func (*AuthorizationService) UpdateAuthorization

func (s *AuthorizationService) UpdateAuthorization(ctx context.Context, id platform.ID, upd *influxdb.AuthorizationUpdate) (*influxdb.Authorization, error)

UpdateAuthorization updates the status and description if available.

type AuthzError

type AuthzError interface {
	error
	AuthzError() error
}

AuthzError is returned for authorization errors. When this error type is returned, the user can be presented with a generic "authorization failed" error, but the system can log the underlying AuthzError() so that operators have insight into what actually failed with authorization.

type BackupBackend

type BackupBackend struct {
	Logger *zap.Logger
	errors.HTTPErrorHandler

	BackupService           influxdb.BackupService
	SqlBackupRestoreService influxdb.SqlBackupRestoreService
	BucketManifestWriter    influxdb.BucketManifestWriter
}

BackupBackend is all services and associated parameters required to construct the BackupHandler.

func NewBackupBackend

func NewBackupBackend(b *APIBackend) *BackupBackend

NewBackupBackend returns a new instance of BackupBackend.

type BackupHandler

type BackupHandler struct {
	*httprouter.Router
	errors.HTTPErrorHandler
	Logger *zap.Logger

	BackupService           influxdb.BackupService
	SqlBackupRestoreService influxdb.SqlBackupRestoreService
	BucketManifestWriter    influxdb.BucketManifestWriter
}

BackupHandler is http handler for backup service.

func NewBackupHandler

func NewBackupHandler(b *BackupBackend) *BackupHandler

NewBackupHandler creates a new handler at /api/v2/backup to receive backup requests.

type Check

type Check struct {
	ID                    platform.ID       `json:"id,omitempty"`
	Name                  string            `json:"name"`
	OrgID                 platform.ID       `json:"orgID,omitempty"`
	OwnerID               platform.ID       `json:"ownerID,omitempty"`
	CreatedAt             time.Time         `json:"createdAt,omitempty"`
	UpdatedAt             time.Time         `json:"updatedAt,omitempty"`
	Query                 *CheckQuery       `json:"query"`
	Status                influxdb.Status   `json:"status"`
	Description           string            `json:"description"`
	LatestCompleted       time.Time         `json:"latestCompleted"`
	LastRunStatus         string            `json:"lastRunStatus"`
	LastRunError          string            `json:"lastRunError"`
	Labels                []*influxdb.Label `json:"labels"`
	Links                 *CheckLinks       `json:"links"`
	Type                  string            `json:"type"`
	TimeSince             string            `json:"timeSince"`
	StaleTime             string            `json:"staleTime"`
	ReportZero            bool              `json:"reportZero"`
	Level                 string            `json:"level"`
	Every                 string            `json:"every"`
	Offset                string            `json:"offset"`
	Tags                  []*influxdb.Tag   `json:"tags"`
	StatusMessageTemplate string            `json:"statusMessageTemplate"`
	Thresholds            []*CheckThreshold `json:"thresholds"`
}

type CheckBackend

type CheckBackend struct {
	errors.HTTPErrorHandler

	AlgoWProxy                 FeatureProxyHandler
	TaskService                taskmodel.TaskService
	CheckService               influxdb.CheckService
	UserResourceMappingService influxdb.UserResourceMappingService
	LabelService               influxdb.LabelService
	UserService                influxdb.UserService
	OrganizationService        influxdb.OrganizationService
	FluxLanguageService        fluxlang.FluxLanguageService
	// contains filtered or unexported fields
}

CheckBackend is all services and associated parameters required to construct the CheckBackendHandler.

func NewCheckBackend

func NewCheckBackend(log *zap.Logger, b *APIBackend) *CheckBackend

NewCheckBackend returns a new instance of CheckBackend.

type CheckBuilderConfig

type CheckBuilderConfig 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"`
	} `json:"aggregateWindow"`
}

type CheckHandler

type CheckHandler struct {
	*httprouter.Router
	errors.HTTPErrorHandler

	TaskService                taskmodel.TaskService
	CheckService               influxdb.CheckService
	UserResourceMappingService influxdb.UserResourceMappingService
	LabelService               influxdb.LabelService
	UserService                influxdb.UserService
	OrganizationService        influxdb.OrganizationService
	FluxLanguageService        fluxlang.FluxLanguageService
	// contains filtered or unexported fields
}

CheckHandler is the handler for the check service

func NewCheckHandler

func NewCheckHandler(log *zap.Logger, b *CheckBackend) *CheckHandler

NewCheckHandler returns a new instance of CheckHandler.

type CheckLinks struct {
	Self    string `json:"self"`
	Labels  string `json:"labels"`
	Members string `json:"members"`
	Owners  string `json:"owners"`
	Query   string `json:"query"`
}

type CheckQuery

type CheckQuery struct {
	Text          string              `json:"text"`
	EditMode      string              `json:"editMode"`
	Name          string              `json:"name"`
	BuilderConfig *CheckBuilderConfig `json:"builderConfig"`
}

type CheckService

type CheckService struct {
	Client *httpc.Client
}

CheckService is a client to interact with the handlers in this package over HTTP. It does not implement influxdb.CheckService because it returns a concrete representation of the API response and influxdb.Check as returned by that interface is not appropriate for this use case.

func (*CheckService) CreateCheck

func (s *CheckService) CreateCheck(ctx context.Context, c *Check) (*Check, error)

CreateCheck creates a new check.

func (*CheckService) DeleteCheck

func (s *CheckService) DeleteCheck(ctx context.Context, id platform.ID) error

DeleteCheck removes a check.

func (*CheckService) FindCheck

func (s *CheckService) FindCheck(ctx context.Context, filter influxdb.CheckFilter) (*Check, error)

FindCheck returns the first check matching the filter.

func (*CheckService) FindCheckByID

func (s *CheckService) FindCheckByID(ctx context.Context, id platform.ID) (*Check, error)

FindCheckByID returns the Check matching the ID.

func (*CheckService) FindChecks

func (s *CheckService) FindChecks(ctx context.Context, filter influxdb.CheckFilter, opt ...influxdb.FindOptions) ([]*Check, int, error)

FindChecks returns a list of checks that match filter and the total count of matching checks. Additional options provide pagination & sorting.

func (*CheckService) PatchCheck

func (s *CheckService) PatchCheck(ctx context.Context, id platform.ID, u influxdb.CheckUpdate) (*Check, error)

PatchCheck changes the status, description or name of a check.

func (*CheckService) UpdateCheck

func (s *CheckService) UpdateCheck(ctx context.Context, id platform.ID, u *Check) (*Check, error)

UpdateCheck updates a check.

type CheckThreshold

type CheckThreshold struct {
	check.ThresholdConfigBase
	Type   string  `json:"type"`
	Value  float64 `json:"value,omitempty"`
	Min    float64 `json:"min,omitempty"`
	Max    float64 `json:"max,omitempty"`
	Within bool    `json:"within"`
}

type Checks

type Checks struct {
	Checks []*Check              `json:"checks"`
	Links  *influxdb.PagingLinks `json:"links"`
}

TODO(gavincabbage): These structures should be in a common place, like other models,

but the common influxdb.Check is an interface that is not appropriate for an API client.

type ConfigHandler added in v2.2.0

type ConfigHandler struct {
	chi.Router
	// contains filtered or unexported fields
}

func NewConfigHandler added in v2.2.0

func NewConfigHandler(log *zap.Logger, opts []cli.Opt) (*ConfigHandler, error)

NewConfigHandler creates a handler that will return a JSON object with key/value pairs for the configuration values used during the launcher startup. The opts slice provides a list of options names along with a pointer to their value.

func (*ConfigHandler) Prefix added in v2.2.0

func (h *ConfigHandler) Prefix() string

type DeleteBackend

type DeleteBackend struct {
	errors.HTTPErrorHandler

	DeleteService       influxdb.DeleteService
	BucketService       influxdb.BucketService
	OrganizationService influxdb.OrganizationService
	// contains filtered or unexported fields
}

DeleteBackend is all services and associated parameters required to construct the DeleteHandler.

func NewDeleteBackend

func NewDeleteBackend(log *zap.Logger, b *APIBackend) *DeleteBackend

NewDeleteBackend returns a new instance of DeleteBackend

type DeleteHandler

type DeleteHandler struct {
	errors.HTTPErrorHandler
	*httprouter.Router

	DeleteService       influxdb.DeleteService
	BucketService       influxdb.BucketService
	OrganizationService influxdb.OrganizationService
	// contains filtered or unexported fields
}

DeleteHandler receives a delete request with a predicate and sends it to storage.

func NewDeleteHandler

func NewDeleteHandler(log *zap.Logger, b *DeleteBackend) *DeleteHandler

NewDeleteHandler creates a new handler at /api/v2/delete to receive delete requests.

type DeleteRequest

type DeleteRequest struct {
	OrgID     string `json:"-"`
	Org       string `json:"-"` // org name
	BucketID  string `json:"-"`
	Bucket    string `json:"-"`
	Start     string `json:"start"`
	Stop      string `json:"stop"`
	Predicate string `json:"predicate"`
}

DeleteRequest is the request send over http to delete points.

type DeleteService

type DeleteService struct {
	Addr               string
	Token              string
	InsecureSkipVerify bool
}

DeleteService sends data over HTTP to delete points.

func (*DeleteService) DeleteBucketRangePredicate

func (s *DeleteService) DeleteBucketRangePredicate(ctx context.Context, dr DeleteRequest) error

DeleteBucketRangePredicate send delete request over http to delete points.

type DocumentBackend

type DocumentBackend struct {
	errors.HTTPErrorHandler

	DocumentService influxdb.DocumentService
	// contains filtered or unexported fields
}

DocumentBackend is all services and associated parameters required to construct the DocumentHandler.

func NewDocumentBackend

func NewDocumentBackend(log *zap.Logger, b *APIBackend) *DocumentBackend

NewDocumentBackend returns a new instance of DocumentBackend.

type DocumentHandler

type DocumentHandler struct {
	*httprouter.Router

	errors.HTTPErrorHandler

	DocumentService influxdb.DocumentService
	LabelService    influxdb.LabelService
	// contains filtered or unexported fields
}

DocumentHandler represents an HTTP API handler for documents.

func NewDocumentHandler

func NewDocumentHandler(b *DocumentBackend) *DocumentHandler

NewDocumentHandler returns a new instance of DocumentHandler. TODO(desa): this should probably take a namespace

type DocumentService

type DocumentService interface {
	GetDocuments(ctx context.Context, namespace string, orgID platform.ID) ([]*influxdb.Document, error)
}

DocumentService is an interface HTTP-exposed portion of the document service.

func NewDocumentService

func NewDocumentService(client *httpc.Client) DocumentService

NewDocumentService creates a client to connect to Influx via HTTP to manage documents.

type FeatureProxyHandler

type FeatureProxyHandler interface {
	Do(w http.ResponseWriter, r *http.Request) bool
}

FeatureProxyHandler is an HTTP proxy that conditionally forwards requests to another backend.

type Flusher

type Flusher interface {
	Flush(ctx context.Context)
}

Flusher flushes data from a store to reset; used for testing.

type FluxBackend

type FluxBackend struct {
	errors2.HTTPErrorHandler

	FluxLogEnabled     bool
	QueryEventRecorder metric.EventRecorder

	AlgoWProxy          FeatureProxyHandler
	OrganizationService influxdb.OrganizationService
	ProxyQueryService   query.ProxyQueryService
	FluxLanguageService fluxlang.FluxLanguageService
	Flagger             feature.Flagger
	// contains filtered or unexported fields
}

FluxBackend is all services and associated parameters required to construct the FluxHandler.

func NewFluxBackend

func NewFluxBackend(log *zap.Logger, b *APIBackend) *FluxBackend

NewFluxBackend returns a new instance of FluxBackend.

type FluxHandler

type FluxHandler struct {
	*httprouter.Router
	errors2.HTTPErrorHandler

	FluxLogEnabled bool

	Now                 func() time.Time
	OrganizationService influxdb.OrganizationService
	ProxyQueryService   query.ProxyQueryService
	FluxLanguageService fluxlang.FluxLanguageService

	EventRecorder metric.EventRecorder

	Flagger feature.Flagger
	// contains filtered or unexported fields
}

FluxHandler implements handling flux queries.

func NewFluxHandler

func NewFluxHandler(log *zap.Logger, b *FluxBackend) *FluxHandler

NewFluxHandler returns a new handler at /api/v2/query for flux queries.

func (*FluxHandler) Prefix

func (*FluxHandler) Prefix() string

Prefix provides the route prefix.

func (*FluxHandler) PrometheusCollectors

func (h *FluxHandler) PrometheusCollectors() []prom.Collector

PrometheusCollectors satisifies the prom.PrometheusCollector interface.

type FluxQueryService

type FluxQueryService struct {
	Addr               string
	Token              string
	Name               string
	InsecureSkipVerify bool
}

FluxQueryService implements query.QueryService by making HTTP requests to the /api/v2/query API endpoint.

func (FluxQueryService) Check

func (*FluxQueryService) Query

Query runs a flux query against a influx server and decodes the result

type FluxService

type FluxService struct {
	Addr               string
	Token              string
	Name               string
	InsecureSkipVerify bool
}

FluxService connects to Influx via HTTP using tokens to run queries.

func (FluxService) Check

func (s FluxService) Check(ctx context.Context) check.Response

func (*FluxService) Query

Query runs a flux query against a influx server and sends the results to the io.Writer. Will use the token from the context over the token within the service struct.

type HTTPDialect

type HTTPDialect interface {
	SetHeaders(w http.ResponseWriter)
}

HTTPDialect is an encoding dialect that can write metadata to HTTP headers

type Handler

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

Handler provides basic handling of metrics, health and debug endpoints. All other requests are passed down to the sub handler.

func NewRootHandler added in v2.0.5

func NewRootHandler(name string, opts ...HandlerOptFn) *Handler

NewRootHandler creates a new handler with the given name and registers any root-level (non-API) routes enabled by the caller.

func (*Handler) PrometheusCollectors

func (h *Handler) PrometheusCollectors() []prometheus.Collector

PrometheusCollectors satisfies prom.PrometheusCollector.

func (*Handler) ServeHTTP

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP delegates a request to the appropriate subhandler.

type HandlerOptFn

type HandlerOptFn func(opts *handlerOpts)

func WithAPIHandler

func WithAPIHandler(h http.Handler) HandlerOptFn

func WithLog

func WithLog(l *zap.Logger) HandlerOptFn

func WithMetrics added in v2.0.5

func WithMetrics(reg *prom.Registry, exposed bool) HandlerOptFn

func WithPprofEnabled added in v2.0.5

func WithPprofEnabled(enabled bool) HandlerOptFn

type LabelBackend

type LabelBackend struct {
	errors.HTTPErrorHandler
	LabelService influxdb.LabelService
	ResourceType influxdb.ResourceType
	// contains filtered or unexported fields
}

LabelBackend is all services and associated parameters required to construct label handlers.

type LabelHandler

type LabelHandler struct {
	*httprouter.Router
	errors.HTTPErrorHandler

	LabelService influxdb.LabelService
	// contains filtered or unexported fields
}

LabelHandler represents an HTTP API handler for labels

func NewLabelHandler

func NewLabelHandler(log *zap.Logger, s influxdb.LabelService, he errors.HTTPErrorHandler) *LabelHandler

NewLabelHandler returns a new instance of LabelHandler

func (*LabelHandler) Prefix

func (h *LabelHandler) Prefix() string

type LabelService

type LabelService struct {
	Client   *httpc.Client
	OpPrefix string
}

LabelService connects to Influx via HTTP using tokens to manage labels

func (*LabelService) CreateLabel

func (s *LabelService) CreateLabel(ctx context.Context, l *influxdb.Label) error

CreateLabel creates a new label.

func (*LabelService) CreateLabelMapping

func (s *LabelService) CreateLabelMapping(ctx context.Context, m *influxdb.LabelMapping) error

CreateLabelMapping will create a labbel mapping

func (*LabelService) DeleteLabel

func (s *LabelService) DeleteLabel(ctx context.Context, id platform.ID) error

DeleteLabel removes a label by ID.

func (*LabelService) DeleteLabelMapping

func (s *LabelService) DeleteLabelMapping(ctx context.Context, m *influxdb.LabelMapping) error

func (*LabelService) FindLabelByID

func (s *LabelService) FindLabelByID(ctx context.Context, id platform.ID) (*influxdb.Label, error)

FindLabelByID returns a single label by ID.

func (*LabelService) FindLabels

func (s *LabelService) FindLabels(ctx context.Context, filter influxdb.LabelFilter, opt ...influxdb.FindOptions) ([]*influxdb.Label, error)

FindLabels is a client for the find labels response from the server.

func (*LabelService) FindResourceLabels

func (s *LabelService) FindResourceLabels(ctx context.Context, filter influxdb.LabelMappingFilter) ([]*influxdb.Label, error)

FindResourceLabels returns a list of labels, derived from a label mapping filter.

func (*LabelService) UpdateLabel

func (s *LabelService) UpdateLabel(ctx context.Context, id platform.ID, upd influxdb.LabelUpdate) (*influxdb.Label, error)

UpdateLabel updates a label and returns the updated label.

type MemberBackend

type MemberBackend struct {
	errors.HTTPErrorHandler

	ResourceType influxdb.ResourceType
	UserType     influxdb.UserType

	UserResourceMappingService influxdb.UserResourceMappingService
	UserService                influxdb.UserService
	// contains filtered or unexported fields
}

MemberBackend is all services and associated parameters required to construct member handler.

type NoopProxyHandler

type NoopProxyHandler struct{}

NoopProxyHandler is a no-op FeatureProxyHandler. It should be used if no feature-flag driven proxying is necessary.

func (*NoopProxyHandler) Do

Do implements FeatureProxyHandler.

type NotificationEndpointBackend

type NotificationEndpointBackend struct {
	errors.HTTPErrorHandler

	NotificationEndpointService influxdb.NotificationEndpointService
	UserResourceMappingService  influxdb.UserResourceMappingService
	LabelService                influxdb.LabelService
	UserService                 influxdb.UserService
	// contains filtered or unexported fields
}

NotificationEndpointBackend is all services and associated parameters required to construct the NotificationEndpointBackendHandler.

func NewNotificationEndpointBackend

func NewNotificationEndpointBackend(log *zap.Logger, b *APIBackend) *NotificationEndpointBackend

NewNotificationEndpointBackend returns a new instance of NotificationEndpointBackend.

func (*NotificationEndpointBackend) Logger

func (b *NotificationEndpointBackend) Logger() *zap.Logger

type NotificationEndpointHandler

type NotificationEndpointHandler struct {
	*httprouter.Router
	errors.HTTPErrorHandler

	NotificationEndpointService influxdb.NotificationEndpointService
	UserResourceMappingService  influxdb.UserResourceMappingService
	LabelService                influxdb.LabelService
	UserService                 influxdb.UserService
	// contains filtered or unexported fields
}

NotificationEndpointHandler is the handler for the notificationEndpoint service

func NewNotificationEndpointHandler

func NewNotificationEndpointHandler(log *zap.Logger, b *NotificationEndpointBackend) *NotificationEndpointHandler

NewNotificationEndpointHandler returns a new instance of NotificationEndpointHandler.

type NotificationEndpointService

type NotificationEndpointService struct {
	Client *httpc.Client
}

NotificationEndpointService is an http client for the influxdb.NotificationEndpointService server implementation.

func NewNotificationEndpointService

func NewNotificationEndpointService(client *httpc.Client) *NotificationEndpointService

NewNotificationEndpointService constructs a new http NotificationEndpointService.

func (*NotificationEndpointService) CreateNotificationEndpoint

func (s *NotificationEndpointService) CreateNotificationEndpoint(ctx context.Context, ne influxdb.NotificationEndpoint, userID platform.ID) error

CreateNotificationEndpoint creates a new notification endpoint and sets b.ID with the new identifier. TODO(@jsteenb2): this is unsatisfactory, we have no way of grabbing the new notification endpoint without

serious hacky hackertoning. Put it on the list...

func (*NotificationEndpointService) DeleteNotificationEndpoint

func (s *NotificationEndpointService) DeleteNotificationEndpoint(ctx context.Context, id platform.ID) ([]influxdb.SecretField, platform.ID, error)

DeleteNotificationEndpoint removes a notification endpoint by ID, returns secret fields, orgID for further deletion. TODO: axe this delete design, makes little sense in how its currently being done. Right now, as an http client,

I am forced to know how the store handles this and then figure out what the server does in between me and that store,
then see what falls out :flushed... for now returning nothing for secrets, orgID, and only returning an error. This makes
the code/design smell super obvious imo

func (*NotificationEndpointService) FindNotificationEndpointByID

func (s *NotificationEndpointService) FindNotificationEndpointByID(ctx context.Context, id platform.ID) (influxdb.NotificationEndpoint, error)

FindNotificationEndpointByID returns a single notification endpoint by ID.

func (*NotificationEndpointService) FindNotificationEndpoints

func (s *NotificationEndpointService) FindNotificationEndpoints(ctx context.Context, filter influxdb.NotificationEndpointFilter, opt ...influxdb.FindOptions) ([]influxdb.NotificationEndpoint, int, error)

FindNotificationEndpoints returns a list of notification endpoints that match filter and the total count of matching notification endpoints. Additional options provide pagination & sorting.

func (*NotificationEndpointService) PatchNotificationEndpoint

func (s *NotificationEndpointService) PatchNotificationEndpoint(ctx context.Context, id platform.ID, upd influxdb.NotificationEndpointUpdate) (influxdb.NotificationEndpoint, error)

PatchNotificationEndpoint updates a single notification endpoint with changeset. Returns the new notification endpoint state after update.

func (*NotificationEndpointService) UpdateNotificationEndpoint

func (s *NotificationEndpointService) UpdateNotificationEndpoint(ctx context.Context, id platform.ID, ne influxdb.NotificationEndpoint, userID platform.ID) (influxdb.NotificationEndpoint, error)

UpdateNotificationEndpoint updates a single notification endpoint. Returns the new notification endpoint after update.

type NotificationRuleBackend

type NotificationRuleBackend struct {
	errors.HTTPErrorHandler

	AlgoWProxy                  FeatureProxyHandler
	NotificationRuleStore       influxdb.NotificationRuleStore
	NotificationEndpointService influxdb.NotificationEndpointService
	UserResourceMappingService  influxdb.UserResourceMappingService
	LabelService                influxdb.LabelService
	UserService                 influxdb.UserService
	OrganizationService         influxdb.OrganizationService
	TaskService                 taskmodel.TaskService
	// contains filtered or unexported fields
}

NotificationRuleBackend is all services and associated parameters required to construct the NotificationRuleBackendHandler.

func NewNotificationRuleBackend

func NewNotificationRuleBackend(log *zap.Logger, b *APIBackend) *NotificationRuleBackend

NewNotificationRuleBackend returns a new instance of NotificationRuleBackend.

type NotificationRuleHandler

type NotificationRuleHandler struct {
	*httprouter.Router
	errors.HTTPErrorHandler

	NotificationRuleStore       influxdb.NotificationRuleStore
	NotificationEndpointService influxdb.NotificationEndpointService
	UserResourceMappingService  influxdb.UserResourceMappingService
	LabelService                influxdb.LabelService
	UserService                 influxdb.UserService
	OrganizationService         influxdb.OrganizationService
	TaskService                 taskmodel.TaskService
	// contains filtered or unexported fields
}

NotificationRuleHandler is the handler for the notification rule service

func NewNotificationRuleHandler

func NewNotificationRuleHandler(log *zap.Logger, b *NotificationRuleBackend) *NotificationRuleHandler

NewNotificationRuleHandler returns a new instance of NotificationRuleHandler.

type NotificationRuleService

type NotificationRuleService struct {
	Client *httpc.Client
}

NotificationRuleService is an http client that implements the NotificationRuleStore interface

func NewNotificationRuleService

func NewNotificationRuleService(client *httpc.Client) *NotificationRuleService

NewNotificationRuleService wraps an httpc.Client in a NotificationRuleService

func (*NotificationRuleService) CreateNotificationRule

func (s *NotificationRuleService) CreateNotificationRule(ctx context.Context, nr influxdb.NotificationRuleCreate, userID platform.ID) error

CreateNotificationRule creates a new NotificationRule from a NotificationRuleCreate the Status on the NotificationRuleCreate is used to determine the status (active/inactive) of the associated Task

func (*NotificationRuleService) DeleteNotificationRule

func (s *NotificationRuleService) DeleteNotificationRule(ctx context.Context, id platform.ID) error

DeleteNotificationRule removes a notification rule by ID.

func (*NotificationRuleService) FindNotificationRuleByID

func (s *NotificationRuleService) FindNotificationRuleByID(ctx context.Context, id platform.ID) (influxdb.NotificationRule, error)

FindNotificationRuleByID finds and returns one Notification Rule with a matching ID

func (*NotificationRuleService) FindNotificationRules

func (s *NotificationRuleService) FindNotificationRules(ctx context.Context, filter influxdb.NotificationRuleFilter, opt ...influxdb.FindOptions) ([]influxdb.NotificationRule, int, error)

FindNotificationRules returns a list of notification rules that match filter and the total count of matching notification rules. Additional options provide pagination & sorting.

func (*NotificationRuleService) PatchNotificationRule

func (s *NotificationRuleService) PatchNotificationRule(ctx context.Context, id platform.ID, upd influxdb.NotificationRuleUpdate) (influxdb.NotificationRule, error)

PatchNotificationRule updates a single notification rule with changeset. Returns the new notification rule state after update.

func (*NotificationRuleService) UpdateNotificationRule

func (s *NotificationRuleService) UpdateNotificationRule(ctx context.Context, id platform.ID, nr influxdb.NotificationRuleCreate, userID platform.ID) (influxdb.NotificationRule, error)

UpdateNotificationRule updates a single notification rule. Returns the new notification rule after update.

type PlatformHandler

type PlatformHandler struct {
	AssetHandler  http.Handler
	DocsHandler   http.HandlerFunc
	APIHandler    http.Handler
	LegacyHandler http.Handler
}

PlatformHandler is a collection of all the service handlers.

func NewPlatformHandler

func NewPlatformHandler(b *APIBackend, opts ...APIHandlerOptFn) *PlatformHandler

NewPlatformHandler returns a platform handler that serves the API and associated assets.

func (*PlatformHandler) ServeHTTP

func (h *PlatformHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP delegates a request to the appropriate subhandler.

type QueryAnalysis

type QueryAnalysis struct {
	Errors []queryParseError `json:"errors"`
}

QueryAnalysis is a structured response of errors.

type QueryDialect

type QueryDialect struct {
	Header         *bool    `json:"header"`
	Delimiter      string   `json:"delimiter"`
	CommentPrefix  string   `json:"commentPrefix"`
	DateTimeFormat string   `json:"dateTimeFormat"`
	Annotations    []string `json:"annotations"`
}

QueryDialect is the formatting options for the query response.

type QueryRequest

type QueryRequest struct {
	Type  string `json:"type"`
	Query string `json:"query"`

	// Flux fields
	Extern  json.RawMessage `json:"extern,omitempty"`
	AST     json.RawMessage `json:"ast,omitempty"`
	Dialect QueryDialect    `json:"dialect"`
	Now     time.Time       `json:"now"`

	Org *influxdb.Organization `json:"-"`

	// PreferNoContent specifies if the Response to this request should
	// contain any result. This is done for avoiding unnecessary
	// bandwidth consumption in certain cases. For example, when the
	// query produces side effects and the results do not matter. E.g.:
	// 	from(...) |> ... |> to()
	// For example, tasks do not use the results of queries, but only
	// care about their side effects.
	// To obtain a QueryRequest with no result, add the header
	// `Prefer: return-no-content` to the HTTP request.
	PreferNoContent bool
	// PreferNoContentWithError is the same as above, but it forces the
	// Response to contain an error if that is a Flux runtime error encoded
	// in the response body.
	// To obtain a QueryRequest with no result but runtime errors,
	// add the header `Prefer: return-no-content-with-error` to the HTTP request.
	PreferNoContentWithError bool
}

QueryRequest is a flux query request.

func QueryRequestFromProxyRequest

func QueryRequestFromProxyRequest(req *query.ProxyRequest) (*QueryRequest, error)

QueryRequestFromProxyRequest converts a query.ProxyRequest into a QueryRequest. The ProxyRequest must contain supported compilers and dialects otherwise an error occurs.

func (QueryRequest) Analyze

Analyze attempts to parse the query request and returns any errors encountered in a structured way.

func (QueryRequest) ProxyRequest

func (r QueryRequest) ProxyRequest() (*query.ProxyRequest, error)

ProxyRequest returns a request to proxy from the flux.

func (QueryRequest) Validate

func (r QueryRequest) Validate() error

Validate checks the query request and returns an error if the request is invalid.

func (QueryRequest) WithDefaults

func (r QueryRequest) WithDefaults() QueryRequest

WithDefaults adds default values to the request.

type RestoreBackend

type RestoreBackend struct {
	Logger *zap.Logger
	errors.HTTPErrorHandler

	RestoreService          influxdb.RestoreService
	SqlBackupRestoreService influxdb.SqlBackupRestoreService
	BucketService           influxdb.BucketService
	AuthorizationService    influxdb.AuthorizationService
}

RestoreBackend is all services and associated parameters required to construct the RestoreHandler.

func NewRestoreBackend

func NewRestoreBackend(b *APIBackend) *RestoreBackend

NewRestoreBackend returns a new instance of RestoreBackend.

type RestoreHandler

type RestoreHandler struct {
	*httprouter.Router

	errors.HTTPErrorHandler
	Logger *zap.Logger

	RestoreService          influxdb.RestoreService
	SqlBackupRestoreService influxdb.SqlBackupRestoreService
	BucketService           influxdb.BucketService
	AuthorizationService    influxdb.AuthorizationService
	// contains filtered or unexported fields
}

RestoreHandler is http handler for restore service.

func NewRestoreHandler

func NewRestoreHandler(b *RestoreBackend) *RestoreHandler

NewRestoreHandler creates a new handler at /api/v2/restore to receive restore requests.

type ScraperBackend

type ScraperBackend struct {
	errors.HTTPErrorHandler

	ScraperStorageService      influxdb.ScraperTargetStoreService
	BucketService              influxdb.BucketService
	OrganizationService        influxdb.OrganizationService
	UserService                influxdb.UserService
	UserResourceMappingService influxdb.UserResourceMappingService
	LabelService               influxdb.LabelService
	// contains filtered or unexported fields
}

ScraperBackend is all services and associated parameters required to construct the ScraperHandler.

func NewScraperBackend

func NewScraperBackend(log *zap.Logger, b *APIBackend) *ScraperBackend

NewScraperBackend returns a new instance of ScraperBackend.

type ScraperHandler

type ScraperHandler struct {
	*httprouter.Router
	errors.HTTPErrorHandler

	UserService                influxdb.UserService
	UserResourceMappingService influxdb.UserResourceMappingService
	LabelService               influxdb.LabelService
	ScraperStorageService      influxdb.ScraperTargetStoreService
	BucketService              influxdb.BucketService
	OrganizationService        influxdb.OrganizationService
	// contains filtered or unexported fields
}

ScraperHandler represents an HTTP API handler for scraper targets.

func NewScraperHandler

func NewScraperHandler(log *zap.Logger, b *ScraperBackend) *ScraperHandler

NewScraperHandler returns a new instance of ScraperHandler.

type ScraperService

type ScraperService struct {
	Addr               string
	Token              string
	InsecureSkipVerify bool
	// OpPrefix is for update invalid ops
	OpPrefix string
}

ScraperService connects to Influx via HTTP using tokens to manage scraper targets.

func (*ScraperService) AddTarget

func (s *ScraperService) AddTarget(ctx context.Context, target *influxdb.ScraperTarget, userID platform.ID) error

AddTarget creates a new scraper target and sets target.ID with the new identifier.

func (*ScraperService) GetTargetByID

func (s *ScraperService) GetTargetByID(ctx context.Context, id platform.ID) (*influxdb.ScraperTarget, error)

GetTargetByID returns a single target by ID.

func (*ScraperService) ListTargets

func (s *ScraperService) ListTargets(ctx context.Context, filter influxdb.ScraperTargetFilter) ([]influxdb.ScraperTarget, error)

ListTargets returns a list of all scraper targets.

func (*ScraperService) RemoveTarget

func (s *ScraperService) RemoveTarget(ctx context.Context, id platform.ID) error

RemoveTarget removes a scraper target by ID.

func (*ScraperService) UpdateTarget

func (s *ScraperService) UpdateTarget(ctx context.Context, update *influxdb.ScraperTarget, userID platform.ID) (*influxdb.ScraperTarget, error)

UpdateTarget updates a single scraper target with changeset. Returns the new target state after update.

type Service

Service connects to an InfluxDB via HTTP.

func NewService

func NewService(httpClient *httpc.Client, addr, token string) (*Service, error)

NewService returns a service that is an HTTP client to a remote. Address and token are needed for those services that do not use httpc.Client, but use those for configuring. Usually one would do:

``` c := NewHTTPClient(addr, token, insecureSkipVerify) s := NewService(c, addr token) ```

So one should provide the same `addr` and `token` to both calls to ensure consistency in the behavior of the returned service.

type SourceBackend

type SourceBackend struct {
	errors.HTTPErrorHandler

	SourceService   influxdb.SourceService
	LabelService    influxdb.LabelService
	BucketService   influxdb.BucketService
	NewQueryService func(s *influxdb.Source) (query.ProxyQueryService, error)
	// contains filtered or unexported fields
}

SourceBackend is all services and associated parameters required to construct the SourceHandler.

func NewSourceBackend

func NewSourceBackend(log *zap.Logger, b *APIBackend) *SourceBackend

NewSourceBackend returns a new instance of SourceBackend.

type SourceHandler

type SourceHandler struct {
	*httprouter.Router
	errors.HTTPErrorHandler

	SourceService influxdb.SourceService
	LabelService  influxdb.LabelService
	BucketService influxdb.BucketService

	// TODO(desa): this was done so in order to remove an import cycle and to allow
	// for http mocking.
	NewQueryService func(s *influxdb.Source) (query.ProxyQueryService, error)
	// contains filtered or unexported fields
}

SourceHandler is a handler for sources

func NewSourceHandler

func NewSourceHandler(log *zap.Logger, b *SourceBackend) *SourceHandler

NewSourceHandler returns a new instance of SourceHandler.

type SourceProxyQueryService

type SourceProxyQueryService struct {
	Addr               string
	InsecureSkipVerify bool
	platform.SourceFields
}

func (*SourceProxyQueryService) Check

func (*SourceProxyQueryService) Query

type SourceService

type SourceService struct {
	Client *httpc.Client
}

SourceService connects to Influx via HTTP using tokens to manage sources

func (*SourceService) CreateSource

func (s *SourceService) CreateSource(ctx context.Context, b *influxdb.Source) error

CreateSource creates a new source and sets b.ID with the new identifier.

func (*SourceService) DeleteSource

func (s *SourceService) DeleteSource(ctx context.Context, id platform.ID) error

DeleteSource removes a source by ID.

func (*SourceService) FindSourceByID

func (s *SourceService) FindSourceByID(ctx context.Context, id platform.ID) (*influxdb.Source, error)

FindSourceByID returns a single source by ID.

func (*SourceService) FindSources

func (s *SourceService) FindSources(ctx context.Context, opt influxdb.FindOptions) ([]*influxdb.Source, int, error)

FindSources returns a list of sources that match filter and the total count of matching sources. Additional options provide pagination & sorting.

func (*SourceService) UpdateSource

func (s *SourceService) UpdateSource(ctx context.Context, id platform.ID, upd influxdb.SourceUpdate) (*influxdb.Source, error)

UpdateSource updates a single source with changeset. Returns the new source state after update.

type SpanTransport

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

SpanTransport injects the http.RoundTripper.RoundTrip() request with a span.

func (*SpanTransport) RoundTrip

func (s *SpanTransport) RoundTrip(r *http.Request) (*http.Response, error)

RoundTrip implements the http.RoundTripper, intercepting the base round trippers call and injecting a span.

type SpecificURMSvc

type SpecificURMSvc struct {
	Client *httpc.Client
	// contains filtered or unexported fields
}

SpecificURMSvc is a URM client that speaks to a specific resource with a specified user type

func (*SpecificURMSvc) CreateUserResourceMapping

func (s *SpecificURMSvc) CreateUserResourceMapping(ctx context.Context, m *influxdb.UserResourceMapping) error

CreateUserResourceMapping will create a user resource mapping

func (*SpecificURMSvc) DeleteUserResourceMapping

func (s *SpecificURMSvc) DeleteUserResourceMapping(ctx context.Context, resourceID platform.ID, userID platform.ID) error

DeleteUserResourceMapping will delete user resource mapping based in criteria.

func (*SpecificURMSvc) FindUserResourceMappings

func (s *SpecificURMSvc) FindUserResourceMappings(ctx context.Context, f influxdb.UserResourceMappingFilter, opt ...influxdb.FindOptions) ([]*influxdb.UserResourceMapping, int, error)

FindUserResourceMappings returns the user resource mappings

type Task

type Task struct {
	ID              platform.ID            `json:"id"`
	OrganizationID  platform.ID            `json:"orgID"`
	Organization    string                 `json:"org"`
	OwnerID         platform.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          string                 `json:"offset,omitempty"`
	LatestCompleted string                 `json:"latestCompleted,omitempty"`
	LastRunStatus   string                 `json:"lastRunStatus,omitempty"`
	LastRunError    string                 `json:"lastRunError,omitempty"`
	CreatedAt       string                 `json:"createdAt,omitempty"`
	UpdatedAt       string                 `json:"updatedAt,omitempty"`
	Metadata        map[string]interface{} `json:"metadata,omitempty"`
}

Task is a package-specific Task format that preserves the expected format for the API, where time values are represented as strings

func NewFrontEndTask

func NewFrontEndTask(t taskmodel.Task) Task

NewFrontEndTask converts a internal task type to a task that we want to display to users

type TaskBackend

type TaskBackend struct {
	errors2.HTTPErrorHandler

	AlgoWProxy                 FeatureProxyHandler
	TaskService                taskmodel.TaskService
	AuthorizationService       influxdb.AuthorizationService
	OrganizationService        influxdb.OrganizationService
	UserResourceMappingService influxdb.UserResourceMappingService
	LabelService               influxdb.LabelService
	UserService                influxdb.UserService
	BucketService              influxdb.BucketService
	// contains filtered or unexported fields
}

TaskBackend is all services and associated parameters required to construct the TaskHandler.

func NewTaskBackend

func NewTaskBackend(log *zap.Logger, b *APIBackend) *TaskBackend

NewTaskBackend returns a new instance of TaskBackend.

type TaskHandler

type TaskHandler struct {
	*httprouter.Router
	errors2.HTTPErrorHandler

	TaskService                taskmodel.TaskService
	AuthorizationService       influxdb.AuthorizationService
	OrganizationService        influxdb.OrganizationService
	UserResourceMappingService influxdb.UserResourceMappingService
	LabelService               influxdb.LabelService
	UserService                influxdb.UserService
	BucketService              influxdb.BucketService
	// contains filtered or unexported fields
}

TaskHandler represents an HTTP API handler for tasks.

func NewTaskHandler

func NewTaskHandler(log *zap.Logger, b *TaskBackend) *TaskHandler

NewTaskHandler returns a new instance of TaskHandler.

type TaskService

type TaskService struct {
	Client *httpc.Client
}

TaskService connects to Influx via HTTP using tokens to manage tasks.

func (TaskService) CancelRun

func (t TaskService) CancelRun(ctx context.Context, taskID, runID platform.ID) error

CancelRun stops a longer running run.

func (TaskService) CreateTask

func (t TaskService) CreateTask(ctx context.Context, tc taskmodel.TaskCreate) (*taskmodel.Task, error)

CreateTask creates a new task.

func (TaskService) DeleteTask

func (t TaskService) DeleteTask(ctx context.Context, id platform.ID) error

DeleteTask removes a task by ID and purges all associated data and scheduled runs.

func (TaskService) FindLogs

func (t TaskService) FindLogs(ctx context.Context, filter taskmodel.LogFilter) ([]*taskmodel.Log, int, error)

FindLogs returns logs for a run.

func (TaskService) FindRunByID

func (t TaskService) FindRunByID(ctx context.Context, taskID, runID platform.ID) (*taskmodel.Run, error)

FindRunByID returns a single run of a specific task.

func (TaskService) FindRuns

func (t TaskService) FindRuns(ctx context.Context, filter taskmodel.RunFilter) ([]*taskmodel.Run, int, error)

FindRuns returns a list of runs that match a filter and the total count of returned runs.

func (TaskService) FindTaskByID

func (t TaskService) FindTaskByID(ctx context.Context, id platform.ID) (*taskmodel.Task, error)

FindTaskByID returns a single task

func (TaskService) FindTasks

func (t TaskService) FindTasks(ctx context.Context, filter taskmodel.TaskFilter) ([]*taskmodel.Task, int, error)

FindTasks returns a list of tasks that match a filter (limit 100) and the total count of matching tasks.

func (TaskService) ForceRun

func (t TaskService) ForceRun(ctx context.Context, taskID platform.ID, scheduledFor int64) (*taskmodel.Run, error)

ForceRun starts a run manually right now.

func (TaskService) RetryRun

func (t TaskService) RetryRun(ctx context.Context, taskID, runID platform.ID) (*taskmodel.Run, error)

RetryRun creates and returns a new run (which is a retry of another run).

func (TaskService) UpdateTask

func (t TaskService) UpdateTask(ctx context.Context, id platform.ID, upd taskmodel.TaskUpdate) (*taskmodel.Task, error)

UpdateTask updates a single task with changeset.

type TelegrafBackend

type TelegrafBackend struct {
	errors.HTTPErrorHandler

	TelegrafService            influxdb.TelegrafConfigStore
	UserResourceMappingService influxdb.UserResourceMappingService
	LabelService               influxdb.LabelService
	UserService                influxdb.UserService
	OrganizationService        influxdb.OrganizationService
	// contains filtered or unexported fields
}

TelegrafBackend is all services and associated parameters required to construct the TelegrafHandler.

func NewTelegrafBackend

func NewTelegrafBackend(log *zap.Logger, b *APIBackend) *TelegrafBackend

NewTelegrafBackend returns a new instance of TelegrafBackend.

type TelegrafHandler

type TelegrafHandler struct {
	*httprouter.Router
	errors.HTTPErrorHandler

	TelegrafService            influxdb.TelegrafConfigStore
	UserResourceMappingService influxdb.UserResourceMappingService
	LabelService               influxdb.LabelService
	UserService                influxdb.UserService
	OrganizationService        influxdb.OrganizationService
	// contains filtered or unexported fields
}

TelegrafHandler is the handler for the telegraf service

func NewTelegrafHandler

func NewTelegrafHandler(log *zap.Logger, b *TelegrafBackend) *TelegrafHandler

NewTelegrafHandler returns a new instance of TelegrafHandler.

type TelegrafService

type TelegrafService struct {
	*UserResourceMappingService
	// contains filtered or unexported fields
}

TelegrafService is an http client that speaks to the telegraf service via HTTP.

func NewTelegrafService

func NewTelegrafService(httpClient *httpc.Client) *TelegrafService

NewTelegrafService is a constructor for a telegraf service.

func (*TelegrafService) CreateTelegrafConfig

func (s *TelegrafService) CreateTelegrafConfig(ctx context.Context, tc *influxdb.TelegrafConfig, userID platform.ID) error

CreateTelegrafConfig creates a new telegraf config and sets b.ID with the new identifier.

func (*TelegrafService) DeleteTelegrafConfig

func (s *TelegrafService) DeleteTelegrafConfig(ctx context.Context, id platform.ID) error

DeleteTelegrafConfig removes a telegraf config by ID.

func (*TelegrafService) FindTelegrafConfigByID

func (s *TelegrafService) FindTelegrafConfigByID(ctx context.Context, id platform.ID) (*influxdb.TelegrafConfig, error)

FindTelegrafConfigByID returns a single telegraf config by ID.

func (*TelegrafService) FindTelegrafConfigs

func (s *TelegrafService) FindTelegrafConfigs(ctx context.Context, f influxdb.TelegrafConfigFilter, opt ...influxdb.FindOptions) ([]*influxdb.TelegrafConfig, int, error)

FindTelegrafConfigs returns a list of telegraf configs that match filter and the total count of matching telegraf configs. Additional options provide pagination & sorting.

func (*TelegrafService) UpdateTelegrafConfig

func (s *TelegrafService) UpdateTelegrafConfig(ctx context.Context, id platform.ID, tc *influxdb.TelegrafConfig, userID platform.ID) (*influxdb.TelegrafConfig, error)

UpdateTelegrafConfig updates a single telegraf config. Returns the new telegraf config after update.

type UserResourceMappingService

type UserResourceMappingService struct {
	Client *httpc.Client
}

UserResourceMappingService is the struct of urm service

func (*UserResourceMappingService) CreateUserResourceMapping

func (s *UserResourceMappingService) CreateUserResourceMapping(ctx context.Context, m *influxdb.UserResourceMapping) error

CreateUserResourceMapping will create a user resource mapping

func (*UserResourceMappingService) DeleteUserResourceMapping

func (s *UserResourceMappingService) DeleteUserResourceMapping(ctx context.Context, resourceID platform.ID, userID platform.ID) error

DeleteUserResourceMapping will delete user resource mapping based in criteria.

func (*UserResourceMappingService) FindUserResourceMappings

func (s *UserResourceMappingService) FindUserResourceMappings(ctx context.Context, f influxdb.UserResourceMappingFilter, opt ...influxdb.FindOptions) ([]*influxdb.UserResourceMapping, int, error)

FindUserResourceMappings returns the user resource mappings

func (*UserResourceMappingService) SpecificURMSvc

func (s *UserResourceMappingService) SpecificURMSvc(rt influxdb.ResourceType, ut influxdb.UserType) *SpecificURMSvc

SpecificURMSvc returns a urm service with specific resource and user types. this will help us stay compatible with the existing service contract but also allow for urm deletes to go through the correct api

type VariableBackend

type VariableBackend struct {
	errors.HTTPErrorHandler

	VariableService influxdb.VariableService
	LabelService    influxdb.LabelService
	// contains filtered or unexported fields
}

VariableBackend is all services and associated parameters required to construct the VariableHandler.

func NewVariableBackend

func NewVariableBackend(log *zap.Logger, b *APIBackend) *VariableBackend

NewVariableBackend creates a backend used by the variable handler.

type VariableHandler

type VariableHandler struct {
	*httprouter.Router

	errors.HTTPErrorHandler

	VariableService influxdb.VariableService
	LabelService    influxdb.LabelService
	// contains filtered or unexported fields
}

VariableHandler is the handler for the variable service

func NewVariableHandler

func NewVariableHandler(log *zap.Logger, b *VariableBackend) *VariableHandler

NewVariableHandler creates a new VariableHandler

type VariableService

type VariableService struct {
	Client *httpc.Client
}

VariableService is a variable service over HTTP to the influxdb server

func (*VariableService) CreateVariable

func (s *VariableService) CreateVariable(ctx context.Context, m *influxdb.Variable) error

CreateVariable creates a new variable and assigns it an influxdb.ID

func (*VariableService) DeleteVariable

func (s *VariableService) DeleteVariable(ctx context.Context, id platform.ID) error

DeleteVariable removes a variable from the store

func (*VariableService) FindVariableByID

func (s *VariableService) FindVariableByID(ctx context.Context, id platform.ID) (*influxdb.Variable, error)

FindVariableByID finds a single variable from the store by its ID

func (*VariableService) FindVariables

func (s *VariableService) FindVariables(ctx context.Context, filter influxdb.VariableFilter, opts ...influxdb.FindOptions) ([]*influxdb.Variable, error)

FindVariables returns a list of variables that match filter. Additional options provide pagination & sorting.

func (*VariableService) ReplaceVariable

func (s *VariableService) ReplaceVariable(ctx context.Context, variable *influxdb.Variable) error

ReplaceVariable replaces a single variable

func (*VariableService) UpdateVariable

func (s *VariableService) UpdateVariable(ctx context.Context, id platform.ID, update *influxdb.VariableUpdate) (*influxdb.Variable, error)

UpdateVariable updates a single variable with a changeset

type WriteBackend

type WriteBackend struct {
	errors.HTTPErrorHandler

	WriteEventRecorder metric.EventRecorder

	PointsWriter        storage.PointsWriter
	BucketService       influxdb.BucketService
	OrganizationService influxdb.OrganizationService
	// contains filtered or unexported fields
}

WriteBackend is all services and associated parameters required to construct the WriteHandler.

func NewWriteBackend

func NewWriteBackend(log *zap.Logger, b *APIBackend) *WriteBackend

NewWriteBackend returns a new instance of WriteBackend.

type WriteHandler

type WriteHandler struct {
	errors.HTTPErrorHandler
	BucketService       influxdb.BucketService
	OrganizationService influxdb.OrganizationService
	PointsWriter        storage.PointsWriter
	EventRecorder       metric.EventRecorder
	// contains filtered or unexported fields
}

WriteHandler receives line protocol and sends to a publish function.

func NewWriteHandler

func NewWriteHandler(log *zap.Logger, b *WriteBackend, opts ...WriteHandlerOption) *WriteHandler

NewWriteHandler creates a new handler at /api/v2/write to receive line protocol.

func (*WriteHandler) Prefix

func (*WriteHandler) Prefix() string

Prefix provides the route prefix.

func (*WriteHandler) ServeHTTP

func (h *WriteHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

type WriteHandlerOption

type WriteHandlerOption func(*WriteHandler)

WriteHandlerOption is a functional option for a *WriteHandler

func WithMaxBatchSizeBytes

func WithMaxBatchSizeBytes(n int64) WriteHandlerOption

WithMaxBatchSizeBytes configures the maximum size for a (decompressed) points batch allowed by the write handler

type WriteService

type WriteService struct {
	Addr               string
	Token              string
	Precision          string
	InsecureSkipVerify bool
}

WriteService sends data over HTTP to influxdb via line protocol.

func (*WriteService) WriteTo

func (s *WriteService) WriteTo(ctx context.Context, filter influxdb.BucketFilter, r io.Reader) error

WriteTo writes to the bucket matching the filter.

type WriteUsageRecorder

type WriteUsageRecorder struct {
	Writer        *kithttp.StatusResponseWriter
	EventRecorder metric.EventRecorder
}

func (*WriteUsageRecorder) Record

func (w *WriteUsageRecorder) Record(ctx context.Context, requestBytes int, orgID platform.ID, endpoint string)

func (*WriteUsageRecorder) Write

func (w *WriteUsageRecorder) Write(b []byte) (int, error)

Directories

Path Synopsis
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.

Jump to

Keyboard shortcuts

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