http

package
v0.0.0-...-d500d3c Latest Latest
Warning

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

Go to latest
Published: Jan 17, 2019 License: MIT Imports: 57 Imported by: 2

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 {
		errors.EncodeHTTP(ctx, err, w)
		return
	}

	// Do stuff here
	if err := h.ThingService.CreateThing(ctx, req.Thing); err != nil {
		errors.EncodeHTTP(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

Overview

NOTE: This service has been deprecated and should not be used. Views are now resources that belong to dashboards. The reason for this is due to how we authorize operations against views.

Index

Constants

View Source
const (
	// Dir is prefix of the assets in the bindata
	Dir = "../../ui/build"
	// Default is the default item to load if 404
	Default = "../../ui/build/index.html"
	// DebugDir is the prefix of the assets in development mode
	DebugDir = "ui/build"
	// DebugDefault is the default item to load if 404
	DebugDefault = "ui/build/index.html"
	// DefaultContentType is the content-type to return for the Default file
	DefaultContentType = "text/html; charset=utf-8"
)
View Source
const (
	// PlatformErrorCodeHeader shows the error code of platform error.
	PlatformErrorCodeHeader = "X-Platform-Error-Code"
	// ErrorHeader is the standard location for influx errors to be reported.
	ErrorHeader = "X-Influx-Error"
	// ReferenceHeader is the header for the reference error reference code.
	ReferenceHeader = "X-Influx-Reference"
)
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 (
	// OrgName is the http query parameter to specify an organization by name.
	OrgName = "org"
	// OrgID is the http query parameter to specify an organization by ID.
	OrgID = "orgID"
)
View Source
const DefaultShutdownTimeout = 20 * time.Second

DefaultShutdownTimeout is the default timeout for shutting down the http server.

Variables

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

errors

View Source
var ErrInvalidDuration = errors.New("invalid duration", errors.MalformedData)

ErrInvalidDuration is returned when parsing a malformatted duration.

View Source
var ErrNotFound = errors.New("no results found")

ErrNotFound is returned when a request for a resource returns no results.

Functions

func CheckError

func CheckError(resp *http.Response, isPlatformError ...bool) (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. THIS IS TEMPORARY. ADD AN OPTIONAL isPlatformError, TO DECODE platform.Error

func CheckErrorStatus

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

CheckErrorStatus for status and any error in the response.

func EncodeError

func EncodeError(ctx context.Context, err error, w http.ResponseWriter)

EncodeError encodes err with the appropriate status code and format, sets the X-Influx-Error and X-Influx-Reference headers on the response, and sets the response status to the corresponding status code.

func ForbiddenError

func ForbiddenError(ctx context.Context, err error, w http.ResponseWriter)

ForbiddenError encodes error with a forbidden status code.

func FormatDuration

func FormatDuration(d time.Duration) string

FormatDuration formats a duration to a string.

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 InjectTrace

func InjectTrace(r *http.Request)

InjectTrace writes any span from the request's context into the request headers.

func ListenAndServe

func ListenAndServe(addr string, handler http.Handler, logger *zap.Logger) error

ListenAndServe is a convenience method for opening a listener using the address and then serving the handler on that address. This method sets up the typical signal handlers.

func NewRouter

func NewRouter() *httprouter.Router

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

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 ReadyHandler

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

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

func SetCookieSession

func SetCookieSession(key string, r *http.Request)

SetCookieSession adds a cookie for the session to an http request

func SetToken

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

SetToken adds the token to the request.

Types

type APIBackend

type APIBackend struct {
	DeveloperMode bool
	Logger        *zap.Logger

	NewBucketService func(*platform.Source) (platform.BucketService, error)
	NewQueryService  func(*platform.Source) (query.ProxyQueryService, error)

	PointsWriter                    storage.PointsWriter
	AuthorizationService            platform.AuthorizationService
	BucketService                   platform.BucketService
	SessionService                  platform.SessionService
	UserService                     platform.UserService
	OrganizationService             platform.OrganizationService
	UserResourceMappingService      platform.UserResourceMappingService
	LabelService                    platform.LabelService
	DashboardService                platform.DashboardService
	DashboardOperationLogService    platform.DashboardOperationLogService
	BucketOperationLogService       platform.BucketOperationLogService
	UserOperationLogService         platform.UserOperationLogService
	OrganizationOperationLogService platform.OrganizationOperationLogService
	SourceService                   platform.SourceService
	MacroService                    platform.MacroService
	BasicAuthService                platform.BasicAuthService
	OnboardingService               platform.OnboardingService
	ProxyQueryService               query.ProxyQueryService
	TaskService                     platform.TaskService
	TelegrafService                 platform.TelegrafConfigStore
	ScraperTargetStoreService       platform.ScraperTargetStoreService
	SecretService                   platform.SecretService
	LookupService                   platform.LookupService
	ChronografService               *server.Service
	ProtoService                    platform.ProtoService
}

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

type APIHandler

type APIHandler struct {
	BucketHandler        *BucketHandler
	UserHandler          *UserHandler
	OrgHandler           *OrgHandler
	AuthorizationHandler *AuthorizationHandler
	DashboardHandler     *DashboardHandler
	AssetHandler         *AssetHandler
	ChronografHandler    *ChronografHandler
	SourceHandler        *SourceHandler
	MacroHandler         *MacroHandler
	TaskHandler          *TaskHandler
	TelegrafHandler      *TelegrafHandler
	QueryHandler         *FluxHandler
	ProtoHandler         *ProtoHandler
	WriteHandler         *WriteHandler
	SetupHandler         *SetupHandler
	SessionHandler       *SessionHandler
}

APIHandler is a collection of all the service handlers.

func NewAPIHandler

func NewAPIHandler(b *APIBackend) *APIHandler

NewAPIHandler constructs all api handlers beneath it and returns an APIHandler

func (*APIHandler) ServeHTTP

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

ServeHTTP delegates a request to the appropriate subhandler.

type AssetHandler

type AssetHandler struct {
	DeveloperMode bool
}

AssetHandler is an http handler for serving chronograf assets.

func NewAssetHandler

func NewAssetHandler() *AssetHandler

NewAssetHandler is the constructor an asset handler.

func (*AssetHandler) ServeHTTP

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

ServeHTTP implements the http handler interface for serving assets.

type AuthenticationHandler

type AuthenticationHandler struct {
	Logger *zap.Logger

	AuthorizationService platform.AuthorizationService
	SessionService       platform.SessionService

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

AuthenticationHandler is a middleware for authenticating incoming requests.

func NewAuthenticationHandler

func NewAuthenticationHandler() *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 AuthorizationHandler

type AuthorizationHandler struct {
	*httprouter.Router
	Logger *zap.Logger

	OrganizationService  platform.OrganizationService
	UserService          platform.UserService
	AuthorizationService platform.AuthorizationService
	LookupService        platform.LookupService
}

AuthorizationHandler represents an HTTP API handler for authorizations.

func NewAuthorizationHandler

func NewAuthorizationHandler(userService platform.UserService) *AuthorizationHandler

NewAuthorizationHandler returns a new instance of AuthorizationHandler.

type AuthorizationService

type AuthorizationService struct {
	Addr               string
	Token              string
	InsecureSkipVerify bool
}

AuthorizationService connects to Influx via HTTP using tokens to manage authorizations

func (*AuthorizationService) CreateAuthorization

func (s *AuthorizationService) CreateAuthorization(ctx context.Context, a *platform.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) (*platform.Authorization, error)

FindAuthorizationByID finds the authorization against a remote influx server.

func (*AuthorizationService) FindAuthorizationByToken

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

FindAuthorizationByToken returns a single authorization by Token.

func (*AuthorizationService) FindAuthorizations

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

func (*AuthorizationService) SetAuthorizationStatus

func (s *AuthorizationService) SetAuthorizationStatus(ctx context.Context, id platform.ID, status platform.Status) error

SetAuthorizationStatus updates an authorization's status.

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 BucketHandler

type BucketHandler struct {
	*httprouter.Router

	Logger *zap.Logger

	BucketService              platform.BucketService
	BucketOperationLogService  platform.BucketOperationLogService
	UserResourceMappingService platform.UserResourceMappingService
	LabelService               platform.LabelService
	UserService                platform.UserService
}

BucketHandler represents an HTTP API handler for buckets.

func NewBucketHandler

func NewBucketHandler(mappingService platform.UserResourceMappingService, labelService platform.LabelService, userService platform.UserService) *BucketHandler

NewBucketHandler returns a new instance of BucketHandler.

type BucketService

type BucketService struct {
	Addr               string
	Token              string
	InsecureSkipVerify bool
	// OpPrefix is an additional property for error
	// find bucket service, when finds nothing.
	OpPrefix string
}

BucketService connects to Influx via HTTP using tokens to manage buckets

func (*BucketService) CreateBucket

func (s *BucketService) CreateBucket(ctx context.Context, b *platform.Bucket) error

CreateBucket creates a new bucket and sets b.ID with the new identifier.

func (*BucketService) DeleteBucket

func (s *BucketService) DeleteBucket(ctx context.Context, id platform.ID) error

DeleteBucket removes a bucket by ID.

func (*BucketService) FindBucket

func (s *BucketService) FindBucket(ctx context.Context, filter platform.BucketFilter) (*platform.Bucket, error)

FindBucket returns the first bucket that matches filter.

func (*BucketService) FindBucketByID

func (s *BucketService) FindBucketByID(ctx context.Context, id platform.ID) (*platform.Bucket, error)

FindBucketByID returns a single bucket by ID.

func (*BucketService) FindBuckets

func (s *BucketService) FindBuckets(ctx context.Context, filter platform.BucketFilter, opt ...platform.FindOptions) ([]*platform.Bucket, int, error)

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

func (*BucketService) UpdateBucket

func (s *BucketService) UpdateBucket(ctx context.Context, id platform.ID, upd platform.BucketUpdate) (*platform.Bucket, error)

UpdateBucket updates a single bucket with changeset. Returns the new bucket state after update.

type ChronografHandler

type ChronografHandler struct {
	*httprouter.Router
	Service *server.Service
}

ChronografHandler is an http handler for serving chronograf chronografs.

func NewChronografHandler

func NewChronografHandler(s *server.Service) *ChronografHandler

NewChronografHandler is the constructor an chronograf handler.

type DashboardHandler

type DashboardHandler struct {
	*httprouter.Router

	Logger *zap.Logger

	DashboardService             platform.DashboardService
	DashboardOperationLogService platform.DashboardOperationLogService
	UserResourceMappingService   platform.UserResourceMappingService
	LabelService                 platform.LabelService
	UserService                  platform.UserService
}

DashboardHandler is the handler for the dashboard service

func NewDashboardHandler

func NewDashboardHandler(mappingService platform.UserResourceMappingService, labelService platform.LabelService, userService platform.UserService) *DashboardHandler

NewDashboardHandler returns a new instance of DashboardHandler.

type DashboardService

type DashboardService struct {
	Addr               string
	Token              string
	InsecureSkipVerify bool
	// OpPrefix is the op prefix for certain errors op.
	OpPrefix string
}

DashboardService is a dashboard service over HTTP to the influxdb server.

func (*DashboardService) AddDashboardCell

AddDashboardCell adds a cell to a dashboard.

func (*DashboardService) CreateDashboard

func (s *DashboardService) CreateDashboard(ctx context.Context, d *platform.Dashboard) error

CreateDashboard creates a new dashboard and sets b.ID with the new identifier.

func (*DashboardService) DeleteDashboard

func (s *DashboardService) DeleteDashboard(ctx context.Context, id platform.ID) error

DeleteDashboard removes a dashboard by ID.

func (*DashboardService) FindDashboardByID

func (s *DashboardService) FindDashboardByID(ctx context.Context, id platform.ID) (*platform.Dashboard, error)

FindDashboardByID returns a single dashboard by ID.

func (*DashboardService) FindDashboards

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

func (*DashboardService) GetDashboardCellView

func (s *DashboardService) GetDashboardCellView(ctx context.Context, dashboardID, cellID platform.ID) (*platform.View, error)

GetDashboardCellView retrieves the view for a dashboard cell.

func (*DashboardService) RemoveDashboardCell

func (s *DashboardService) RemoveDashboardCell(ctx context.Context, dashboardID, cellID platform.ID) error

RemoveDashboardCell removes a dashboard.

func (*DashboardService) ReplaceDashboardCells

func (s *DashboardService) ReplaceDashboardCells(ctx context.Context, id platform.ID, cs []*platform.Cell) error

ReplaceDashboardCells replaces all cells in a dashboard

func (*DashboardService) UpdateDashboard

UpdateDashboard updates a single dashboard with changeset. Returns the new dashboard state after update.

func (*DashboardService) UpdateDashboardCell

func (s *DashboardService) UpdateDashboardCell(ctx context.Context, dashboardID, cellID platform.ID, upd platform.CellUpdate) (*platform.Cell, error)

UpdateDashboardCell replaces the dashboard cell with the provided ID.

func (*DashboardService) UpdateDashboardCellView

func (s *DashboardService) UpdateDashboardCellView(ctx context.Context, dashboardID, cellID platform.ID, upd platform.ViewUpdate) (*platform.View, error)

UpdateDashboardCellView updates the view for a dashboard cell.

type FluxHandler

type FluxHandler struct {
	*httprouter.Router

	Logger *zap.Logger

	Now                 func() time.Time
	OrganizationService platform.OrganizationService
	ProxyQueryService   query.ProxyQueryService
}

FluxHandler implements handling flux queries.

func NewFluxHandler

func NewFluxHandler() *FluxHandler

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

func (*FluxHandler) PrometheusCollectors

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

PrometheusCollectors satisifies the prom.PrometheusCollector interface.

type FluxQueryService

type FluxQueryService struct {
	Addr               string
	Token              string
	InsecureSkipVerify bool
}

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

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
	InsecureSkipVerify bool
}

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

func (*FluxService) Query

func (s *FluxService) Query(ctx context.Context, w io.Writer, r *query.ProxyRequest) (int64, error)

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 {

	// MetricsHandler handles metrics requests
	MetricsHandler http.Handler
	// ReadyHandler handles readiness checks
	ReadyHandler http.Handler
	// HealthHandler handles health requests
	HealthHandler http.Handler
	// DebugHandler handles debug requests
	DebugHandler http.Handler
	// Handler handles all other requests
	Handler http.Handler

	// Logger if set will log all HTTP requests as they are served
	Logger *zap.Logger

	// Tracer if set will be used to propagate traces through HTTP requests
	Tracer opentracing.Tracer
	// 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 NewHandler

func NewHandler(name string) *Handler

NewHandler creates a new handler with the given name. The name is used to tag the metrics produced by this handler.

The MetricsHandler is set to the default prometheus handler. It is the caller's responsibility to call prometheus.MustRegister(h.PrometheusCollectors()...). In most cases, you want to use NewHandlerFromRegistry instead.

func NewHandlerFromRegistry

func NewHandlerFromRegistry(name string, reg *prom.Registry) *Handler

NewHandlerFromRegistry creates a new handler with the given name, and sets the /metrics endpoint to use the metrics from the given registry, after self-registering h's metrics.

func (*Handler) PrometheusCollectors

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

PrometheusCollectors satisifies prom.PrometheusCollector.

func (*Handler) ServeHTTP

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

ServeHTTP delegates a request to the appropriate subhandler.

type LabelService

type LabelService struct {
	Addr               string
	Token              string
	InsecureSkipVerify bool
	BasePath           string
}

func (*LabelService) CreateLabel

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

func (*LabelService) DeleteLabel

func (s *LabelService) DeleteLabel(ctx context.Context, l plat.Label) error

func (*LabelService) FindLabels

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

FindLabels returns a slice of labels

type MacroHandler

type MacroHandler struct {
	*httprouter.Router

	Logger *zap.Logger

	MacroService platform.MacroService
}

MacroHandler is the handler for the macro service

func NewMacroHandler

func NewMacroHandler() *MacroHandler

NewMacroHandler creates a new MacroHandler

type MacroService

type MacroService struct {
	Addr               string
	Token              string
	InsecureSkipVerify bool
}

MacroService is a macro service over HTTP to the influxdb server

func (*MacroService) CreateMacro

func (s *MacroService) CreateMacro(ctx context.Context, m *platform.Macro) error

CreateMacro creates a new macro and assigns it an platform.ID

func (*MacroService) DeleteMacro

func (s *MacroService) DeleteMacro(ctx context.Context, id platform.ID) error

DeleteMacro removes a macro from the store

func (*MacroService) FindMacroByID

func (s *MacroService) FindMacroByID(ctx context.Context, id platform.ID) (*platform.Macro, error)

FindMacroByID finds a single macro from the store by its ID

func (*MacroService) FindMacros

func (s *MacroService) FindMacros(ctx context.Context) ([]*platform.Macro, error)

FindMacros returns all macros in the store

func (*MacroService) ReplaceMacro

func (s *MacroService) ReplaceMacro(ctx context.Context, macro *platform.Macro) error

ReplaceMacro replaces a single macro

func (*MacroService) UpdateMacro

func (s *MacroService) UpdateMacro(ctx context.Context, id platform.ID, update *platform.MacroUpdate) (*platform.Macro, error)

UpdateMacro updates a single macro with a changeset

type OrgHandler

type OrgHandler struct {
	*httprouter.Router

	Logger *zap.Logger

	OrganizationService             platform.OrganizationService
	OrganizationOperationLogService platform.OrganizationOperationLogService
	BucketService                   platform.BucketService
	UserResourceMappingService      platform.UserResourceMappingService
	SecretService                   platform.SecretService
	LabelService                    platform.LabelService
	UserService                     platform.UserService
}

OrgHandler represents an HTTP API handler for orgs.

func NewOrgHandler

func NewOrgHandler(mappingService platform.UserResourceMappingService,
	labelService platform.LabelService, userService platform.UserService) *OrgHandler

NewOrgHandler returns a new instance of OrgHandler.

type OrganizationService

type OrganizationService struct {
	Addr               string
	Token              string
	InsecureSkipVerify bool
	// OpPrefix is for not found errors.
	OpPrefix string
}

OrganizationService connects to Influx via HTTP using tokens to manage organizations.

func (*OrganizationService) CreateOrganization

func (s *OrganizationService) CreateOrganization(ctx context.Context, o *platform.Organization) error

CreateOrganization creates an organization.

func (*OrganizationService) DeleteOrganization

func (s *OrganizationService) DeleteOrganization(ctx context.Context, id platform.ID) error

DeleteOrganization removes organization id over HTTP.

func (*OrganizationService) FindOrganization

FindOrganization gets a single organization matching the filter using HTTP.

func (*OrganizationService) FindOrganizationByID

func (s *OrganizationService) FindOrganizationByID(ctx context.Context, id platform.ID) (*platform.Organization, error)

FindOrganizationByID gets a single organization with a given id using HTTP.

func (*OrganizationService) FindOrganizations

FindOrganizations returns all organizations that match the filter via HTTP.

func (*OrganizationService) UpdateOrganization

UpdateOrganization updates the organization over HTTP.

type PlatformHandler

type PlatformHandler struct {
	AssetHandler *AssetHandler
	APIHandler   http.Handler
}

PlatformHandler is a collection of all the service handlers.

func NewPlatformHandler

func NewPlatformHandler(b *APIBackend) *PlatformHandler

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

func (*PlatformHandler) PrometheusCollectors

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

PrometheusCollectors satisfies the prom.PrometheusCollector interface.

func (*PlatformHandler) ServeHTTP

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

ServeHTTP delegates a request to the appropriate subhandler.

type ProtoBackend

type ProtoBackend struct {
	Logger       *zap.Logger
	ProtoService platform.ProtoService
	LabelService platform.LabelService
}

ProtoBackend is the backend for the proto handler.

func NewProtoBackend

func NewProtoBackend(b *APIBackend) *ProtoBackend

NewProtoBackend creates an instance of the Protobackend from the APIBackend.

type ProtoHandler

type ProtoHandler struct {
	*httprouter.Router
	Logger       *zap.Logger
	ProtoService platform.ProtoService
	LabelService platform.LabelService
}

ProtoHandler is the handler for creating instances of prebuilt resources (dashboards, tasks, etcd).

func NewProtoHandler

func NewProtoHandler(b *ProtoBackend) *ProtoHandler

NewProtoHandler creates an instance of a proto handler.

type ProxyQueryHandler

type ProxyQueryHandler struct {
	*httprouter.Router

	Logger *zap.Logger

	ProxyQueryService query.ProxyQueryService

	CompilerMappings flux.CompilerMappings
	DialectMappings  flux.DialectMappings
}

func NewProxyQueryHandler

func NewProxyQueryHandler() *ProxyQueryHandler

NewProxyQueryHandler returns a new instance of ProxyQueryHandler.

func (*ProxyQueryHandler) PrometheusCollectors

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

PrometheusCollectors satisifies the prom.PrometheusCollector interface.

type ProxyQueryService

type ProxyQueryService struct {
	Addr               string
	Token              string
	InsecureSkipVerify bool
}

func (*ProxyQueryService) Query

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 QueryHandler

type QueryHandler struct {
	*httprouter.Router

	Logger *zap.Logger

	QueryService     query.QueryService
	CompilerMappings flux.CompilerMappings
	// contains filtered or unexported fields
}

func NewQueryHandler

func NewQueryHandler() *QueryHandler

NewQueryHandler returns a new instance of QueryHandler.

func (*QueryHandler) PrometheusCollectors

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

PrometheusCollectors satisifies the prom.PrometheusCollector interface.

type QueryRequest

type QueryRequest struct {
	Spec    *flux.Spec   `json:"spec,omitempty"`
	AST     *ast.Package `json:"ast,omitempty"`
	Query   string       `json:"query"`
	Type    string       `json:"type"`
	Dialect QueryDialect `json:"dialect"`

	Org *platform.Organization `json:"-"`
}

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

func (r QueryRequest) Analyze() (*QueryAnalysis, error)

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 QueryService

type QueryService struct {
	Addr               string
	Token              string
	InsecureSkipVerify bool
}

func (*QueryService) Ping

func (s *QueryService) Ping(ctx context.Context) error

Ping checks to see if the server is responding to a ping request.

func (*QueryService) Query

Query calls the query route with the requested query and returns a result iterator.

type ScraperHandler

type ScraperHandler struct {
	*httprouter.Router
	Logger                *zap.Logger
	ScraperStorageService platform.ScraperTargetStoreService
}

ScraperHandler represents an HTTP API handler for scraper targets.

func NewScraperHandler

func NewScraperHandler() *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 *platform.ScraperTarget) 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) (*platform.ScraperTarget, error)

GetTargetByID returns a single target by ID.

func (*ScraperService) ListTargets

func (s *ScraperService) ListTargets(ctx context.Context) ([]platform.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 *platform.ScraperTarget) (*platform.ScraperTarget, error)

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

type Server

type Server struct {
	ShutdownTimeout time.Duration
	// contains filtered or unexported fields
}

Server is an abstraction around the http.Server that handles a server process. It manages the full lifecycle of a server by serving a handler on a socket. If signals have been registered, it will attempt to terminate the server using Shutdown if a signal is received and will force a shutdown if a second signal is received.

func NewServer

func NewServer(handler http.Handler, logger *zap.Logger) *Server

NewServer returns a new server struct that can be used.

func (*Server) ListenForSignals

func (s *Server) ListenForSignals(signals ...os.Signal)

ListenForSignals registers the the server to listen for the given signals to shutdown the server. The signals are not captured until Serve is called.

func (*Server) Serve

func (s *Server) Serve(listener net.Listener) error

Serve will run the server using the listener to accept connections.

type Service

Service connects to an InfluxDB via HTTP.

func NewService

func NewService(addr, token string) *Service

NewService returns a service that is an HTTP client to a remote

type SessionBackend

type SessionBackend struct {
	Logger *zap.Logger

	BasicAuthService platform.BasicAuthService
	SessionService   platform.SessionService
}

SessionBackend is all services and associated parameters required to construct the SessionHandler.

func NewSessionBackend

func NewSessionBackend(b *APIBackend) *SessionBackend

type SessionHandler

type SessionHandler struct {
	*httprouter.Router
	Logger *zap.Logger

	BasicAuthService platform.BasicAuthService
	SessionService   platform.SessionService
}

SessionHandler represents an HTTP API handler for authorizations.

func NewSessionHandler

func NewSessionHandler(b *SessionBackend) *SessionHandler

NewSessionHandler returns a new instance of SessionHandler.

type SetupHandler

type SetupHandler struct {
	*httprouter.Router

	Logger *zap.Logger

	OnboardingService platform.OnboardingService
}

SetupHandler represents an HTTP API handler for onboarding setup.

func NewSetupHandler

func NewSetupHandler() *SetupHandler

NewSetupHandler returns a new instance of SetupHandler.

type SetupService

type SetupService struct {
	Addr               string
	InsecureSkipVerify bool
}

SetupService connects to Influx via HTTP to perform onboarding operations

func (*SetupService) Generate

Generate OnboardingResults.

func (*SetupService) IsOnboarding

func (s *SetupService) IsOnboarding(ctx context.Context) (bool, error)

IsOnboarding determine if onboarding request is allowed.

type SourceHandler

type SourceHandler struct {
	*httprouter.Router
	Logger        *zap.Logger
	SourceService platform.SourceService

	// TODO(desa): this was done so in order to remove an import cycle and to allow
	// for http mocking.
	NewBucketService func(s *platform.Source) (platform.BucketService, error)
	NewQueryService  func(s *platform.Source) (query.ProxyQueryService, error)
}

SourceHandler is a handler for sources

func NewSourceHandler

func NewSourceHandler() *SourceHandler

NewSourceHandler returns a new instance of SourceHandler.

type SourceProxyQueryService

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

func (*SourceProxyQueryService) Query

type SourceService

type SourceService struct {
	Addr               string
	Token              string
	InsecureSkipVerify bool
}

SourceService connects to Influx via HTTP using tokens to manage sources

func (*SourceService) CreateSource

func (s *SourceService) CreateSource(ctx context.Context, b *platform.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) (*platform.Source, error)

FindSourceByID returns a single source by ID.

func (*SourceService) FindSources

func (s *SourceService) FindSources(ctx context.Context, opt platform.FindOptions) ([]*platform.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 platform.SourceUpdate) (*platform.Source, error)

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

type TaskHandler

type TaskHandler struct {
	*httprouter.Router

	TaskService                platform.TaskService
	AuthorizationService       platform.AuthorizationService
	OrganizationService        platform.OrganizationService
	UserResourceMappingService platform.UserResourceMappingService
	LabelService               platform.LabelService
	UserService                platform.UserService
	// contains filtered or unexported fields
}

TaskHandler represents an HTTP API handler for tasks.

func NewTaskHandler

func NewTaskHandler(mappingService platform.UserResourceMappingService, labelService platform.LabelService, logger *zap.Logger, userService platform.UserService) *TaskHandler

NewTaskHandler returns a new instance of TaskHandler.

type TaskService

type TaskService struct {
	Addr               string
	Token              string
	InsecureSkipVerify bool
}

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

func (TaskService) CreateTask

func (t TaskService) CreateTask(ctx context.Context, tsk *platform.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 platform.LogFilter) ([]*platform.Log, int, error)

FindLogs returns logs for a run.

func (TaskService) FindRunByID

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

FindRunByID returns a single run of a specific task.

func (TaskService) FindRuns

func (t TaskService) FindRuns(ctx context.Context, filter platform.RunFilter) ([]*platform.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) (*platform.Task, error)

FindTaskByID returns a single task

func (TaskService) FindTasks

func (t TaskService) FindTasks(ctx context.Context, filter platform.TaskFilter) ([]*platform.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) (*platform.Run, error)

func (TaskService) RetryRun

func (t TaskService) RetryRun(ctx context.Context, taskID, runID platform.ID) (*platform.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 platform.TaskUpdate) (*platform.Task, error)

UpdateTask updates a single task with changeset.

type TelegrafHandler

type TelegrafHandler struct {
	*httprouter.Router
	Logger *zap.Logger

	TelegrafService            platform.TelegrafConfigStore
	UserResourceMappingService platform.UserResourceMappingService
	LabelService               platform.LabelService
	UserService                platform.UserService
}

TelegrafHandler is the handler for the telegraf service

func NewTelegrafHandler

func NewTelegrafHandler(
	logger *zap.Logger,
	mappingService platform.UserResourceMappingService,
	labelService platform.LabelService,
	telegrafSvc platform.TelegrafConfigStore,
	userService platform.UserService,
) *TelegrafHandler

NewTelegrafHandler returns a new instance of TelegrafHandler.

type UsageHandler

type UsageHandler struct {
	*httprouter.Router

	Logger *zap.Logger

	UsageService platform.UsageService
}

UsageHandler represents an HTTP API handler for usages.

func NewUsageHandler

func NewUsageHandler() *UsageHandler

NewUsageHandler returns a new instance of UsageHandler.

type UserHandler

type UserHandler struct {
	*httprouter.Router
	UserService             platform.UserService
	UserOperationLogService platform.UserOperationLogService
	BasicAuthService        platform.BasicAuthService
}

UserHandler represents an HTTP API handler for users.

func NewUserHandler

func NewUserHandler() *UserHandler

NewUserHandler returns a new instance of UserHandler.

type UserResourceMappingService

type UserResourceMappingService struct {
	Addr               string
	Token              string
	InsecureSkipVerify bool
	BasePath           string
}

TODO(jm): how is basepath going to be populated?

func (*UserResourceMappingService) CreateUserResourceMapping

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

func (*UserResourceMappingService) DeleteUserResourceMapping

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

func (*UserResourceMappingService) FindUserResourceMappings

type UserService

type UserService struct {
	Addr               string
	Token              string
	InsecureSkipVerify bool
	// OpPrefix is the ops of not found error.
	OpPrefix string
}

UserService connects to Influx via HTTP using tokens to manage users

func (*UserService) CreateUser

func (s *UserService) CreateUser(ctx context.Context, u *platform.User) error

CreateUser creates a new user and sets u.ID with the new identifier.

func (*UserService) DeleteUser

func (s *UserService) DeleteUser(ctx context.Context, id platform.ID) error

DeleteUser removes a user by ID.

func (*UserService) FindMe

func (s *UserService) FindMe(ctx context.Context, id platform.ID) (*platform.User, error)

FindMe returns user information about the owner of the token

func (*UserService) FindUser

func (s *UserService) FindUser(ctx context.Context, filter platform.UserFilter) (*platform.User, error)

FindUser returns the first user that matches filter.

func (*UserService) FindUserByID

func (s *UserService) FindUserByID(ctx context.Context, id platform.ID) (*platform.User, error)

FindUserByID returns a single user by ID.

func (*UserService) FindUsers

func (s *UserService) FindUsers(ctx context.Context, filter platform.UserFilter, opt ...platform.FindOptions) ([]*platform.User, int, error)

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

func (*UserService) UpdateUser

func (s *UserService) UpdateUser(ctx context.Context, id platform.ID, upd platform.UserUpdate) (*platform.User, error)

UpdateUser updates a single user with changeset. Returns the new user state after update.

type ViewHandler

type ViewHandler struct {
	*httprouter.Router

	Logger *zap.Logger

	ViewService                platform.ViewService
	UserResourceMappingService platform.UserResourceMappingService
	LabelService               platform.LabelService
	UserService                platform.UserService
}

ViewHandler is the handler for the view service

func NewViewHandler

func NewViewHandler(mappingService platform.UserResourceMappingService, labelService platform.LabelService, userService platform.UserService) *ViewHandler

NewViewHandler returns a new instance of ViewHandler.

type WriteHandler

type WriteHandler struct {
	*httprouter.Router

	Logger *zap.Logger

	BucketService       platform.BucketService
	OrganizationService platform.OrganizationService

	PointsWriter storage.PointsWriter
}

WriteHandler receives line protocol and sends to a publish function.

func NewWriteHandler

func NewWriteHandler(writer storage.PointsWriter) *WriteHandler

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

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) Write

func (s *WriteService) Write(ctx context.Context, orgID, bucketID platform.ID, r io.Reader) error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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