backend

package
v0.188.3 Latest Latest
Warning

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

Go to latest
Published: Jan 15, 2024 License: Apache-2.0 Imports: 44 Imported by: 15

Documentation

Overview

Package backend provides SDK handler interfaces and contracts for implementing and serving backend plugins.

Index

Constants

View Source
const (
	// OAuthIdentityTokenHeaderName the header name used for forwarding
	// OAuth Identity access token.
	OAuthIdentityTokenHeaderName = "Authorization"

	// OAuthIdentityIDTokenHeaderName the header name used for forwarding
	// OAuth Identity ID token.
	OAuthIdentityIDTokenHeaderName = "X-Id-Token"

	// CookiesHeaderName the header name used for forwarding
	// cookies.
	CookiesHeaderName = "Cookie"
)
View Source
const (
	// PluginProfilerEnvDeprecated is a deprecated constant for the GF_PLUGINS_PROFILER environment variable used to enable pprof.
	PluginProfilerEnvDeprecated = "GF_PLUGINS_PROFILER"
	// PluginProfilingEnabledEnv is a constant for the GF_PLUGIN_PROFILING_ENABLED environment variable used to enable pprof.
	PluginProfilingEnabledEnv = "GF_PLUGIN_PROFILING_ENABLED"

	// PluginProfilerPortEnvDeprecated is a constant for the GF_PLUGINS_PROFILER_PORT environment variable use to specify a pprof port (default 6060).
	PluginProfilerPortEnvDeprecated = "GF_PLUGINS_PROFILER_PORT" // nolint:gosec
	// PluginProfilingPortEnv is a constant for the GF_PLUGIN_PROFILING_PORT environment variable use to specify a pprof port (default 6060).
	PluginProfilingPortEnv = "GF_PLUGIN_PROFILING_PORT" // nolint:gosec

	// PluginTracingOpenTelemetryOTLPAddressEnv is a constant for the GF_INSTANCE_OTLP_ADDRESS
	// environment variable used to specify the OTLP address.
	PluginTracingOpenTelemetryOTLPAddressEnv = "GF_INSTANCE_OTLP_ADDRESS" // nolint:gosec
	// PluginTracingOpenTelemetryOTLPPropagationEnv is a constant for the GF_INSTANCE_OTLP_PROPAGATION
	// environment variable used to specify the OTLP propagation format.
	PluginTracingOpenTelemetryOTLPPropagationEnv = "GF_INSTANCE_OTLP_PROPAGATION"

	// PluginTracingSamplerTypeEnv is a constant for the GF_INSTANCE_OTLP_SAMPLER_TYPE
	// environment variable used to specify the OTLP sampler type.
	PluginTracingSamplerTypeEnv = "GF_INSTANCE_OTLP_SAMPLER_TYPE"

	// PluginTracingSamplerParamEnv is a constant for the GF_INSTANCE_OTLP_SAMPLER_PARAM
	// environment variable used to specify an additional float parameter used by the OTLP sampler,
	// depending on the type.
	PluginTracingSamplerParamEnv = "GF_INSTANCE_OTLP_SAMPLER_PARAM"

	// PluginTracingSamplerRemoteURL is a constant for the GF_INSTANCE_OTLP_SAMPLER_REMOTE_URL
	// environment variable used to specify the remote url for the sampler type. This is relevant
	// only when GF_INSTANCE_OTLP_SAMPLER_TYPE is "remote".
	PluginTracingSamplerRemoteURL = "GF_INSTANCE_OTLP_SAMPLER_REMOTE_URL"

	// PluginVersionEnv is a constant for the GF_PLUGIN_VERSION environment variable containing the plugin's version.
	// Deprecated: Use build.GetBuildInfo().Version instead.
	PluginVersionEnv = "GF_PLUGIN_VERSION"
)
View Source
const (
	AppURL = "GF_APP_URL"
)

Variables

Logger is the default logger instance. This can be used directly to log from your plugin to grafarg-server with calls like backend.Logger.Debug(...).

View Source
var NewLoggerWith = func(args ...interface{}) log.Logger {
	return log.New().With(args...)
}

NewLoggerWith creates a new logger with the given arguments.

Functions

func GracefulStandaloneServe

func GracefulStandaloneServe(dsopts ServeOpts, info standalone.ServerSettings) error

GracefulStandaloneServe starts a gRPC server that is not managed by hashicorp. The provided standalone.Args must have an address set, or the function returns an error. The function handles creating/cleaning up the standalone address file, and graceful GRPC server termination. The function returns after the GRPC server has been terminated.

func JSONDataFromHTTPClientOptions

func JSONDataFromHTTPClientOptions(opts httpclient.Options) (res map[string]interface{})

JSONDataFromHTTPClientOptions extracts JSON data from CustomOptions of httpclient.Options.

func Manage

func Manage(pluginID string, serveOpts ServeOpts) error

Manage runs the plugin in either standalone mode, dummy locator or normal (hashicorp) mode.

func SecureJSONDataFromHTTPClientOptions

func SecureJSONDataFromHTTPClientOptions(opts httpclient.Options) (res map[string]string)

SecureJSONDataFromHTTPClientOptions extracts secure JSON data from CustomOptions of httpclient.Options.

func Serve

func Serve(opts ServeOpts) error

Serve starts serving the plugin over gRPC.

func SetupPluginEnvironment

func SetupPluginEnvironment(pluginID string)

SetupPluginEnvironment will read the environment variables and apply the standard environment behavior.

As the SDK evolves, this will likely change.

Currently, this function enables and configures profiling with pprof.

func SetupTracer

func SetupTracer(pluginID string, tracingOpts tracing.Opts) error

SetupTracer sets up the global OTEL trace provider and tracer.

func TestStandaloneServe

func TestStandaloneServe(opts ServeOpts, address string) (*grpc.Server, error)

TestStandaloneServe starts a gRPC server that is not managed by hashicorp. The function returns the gRPC server which should be closed by the consumer.

func UserAgentFromContext

func UserAgentFromContext(ctx context.Context) *useragent.UserAgent

UserAgentFromContext returns user agent from context.

func WithGrafargConfig

func WithGrafargConfig(ctx context.Context, cfg *GrafargCfg) context.Context

WithGrafargConfig injects supplied Grafarg config into context.

func WithUserAgent

func WithUserAgent(ctx context.Context, ua *useragent.UserAgent) context.Context

WithUserAgent injects supplied user agent into context.

Types

type AppInstanceSettings

type AppInstanceSettings struct {
	// JSONData repeats the properties at this level of the object (excluding DataSourceConfig), and also includes any
	// custom properties associated with the plugin config instance.
	JSONData json.RawMessage

	// DecryptedSecureJSONData contains key,value pairs where the encrypted configuration plugin instance in Grafarg
	// server have been decrypted before passing them to the plugin.
	DecryptedSecureJSONData map[string]string

	// Updated is the last time this plugin instance's configuration was updated.
	Updated time.Time
}

AppInstanceSettings represents settings for an app instance.

In Grafarg an app instance is an app plugin of certain type that have been configured and enabled in a Grafarg organization.

func (*AppInstanceSettings) HTTPClientOptions

func (s *AppInstanceSettings) HTTPClientOptions(_ context.Context) (httpclient.Options, error)

HTTPClientOptions creates httpclient.Options based on settings.

type CallResourceHandler

type CallResourceHandler interface {
	CallResource(ctx context.Context, req *CallResourceRequest, sender CallResourceResponseSender) error
}

CallResourceHandler handles resource calls.

type CallResourceHandlerFunc

type CallResourceHandlerFunc func(ctx context.Context, req *CallResourceRequest, sender CallResourceResponseSender) error

CallResourceHandlerFunc is an adapter to allow the use of ordinary functions as backend.CallResourceHandler. If f is a function with the appropriate signature, CallResourceHandlerFunc(f) is a Handler that calls f.

func (CallResourceHandlerFunc) CallResource

CallResource calls fn(ctx, req, sender).

type CallResourceRequest

type CallResourceRequest struct {
	// PluginContext the contextual information for the request.
	PluginContext PluginContext

	// Path the forwarded HTTP path for the request.
	Path string

	// Method the forwarded HTTP method for the request.
	Method string

	// URL the forwarded HTTP URL for the request.
	URL string

	// Headers the forwarded HTTP headers for the request, if any.
	//
	// Recommended to use GetHTTPHeaders or GetHTTPHeader
	// since it automatically handles canonicalization of
	// HTTP header keys.
	Headers map[string][]string

	// Body the forwarded HTTP body for the request, if any.
	Body []byte
}

CallResourceRequest represents a request for a resource call.

func (*CallResourceRequest) DeleteHTTPHeader

func (req *CallResourceRequest) DeleteHTTPHeader(key string)

DeleteHTTPHeader deletes the values associated with key. The key is case insensitive; it is canonicalized by CanonicalHeaderKey.

func (*CallResourceRequest) GetHTTPHeader

func (req *CallResourceRequest) GetHTTPHeader(key string) string

GetHTTPHeader gets the first value associated with the given key. If there are no values associated with the key, Get returns "". It is case insensitive; textproto.CanonicalMIMEHeaderKey is used to canonicalize the provided key. Get assumes that all keys are stored in canonical form.

func (*CallResourceRequest) GetHTTPHeaders

func (req *CallResourceRequest) GetHTTPHeaders() http.Header

GetHTTPHeaders returns HTTP headers.

func (*CallResourceRequest) SetHTTPHeader

func (req *CallResourceRequest) SetHTTPHeader(key, value string)

SetHTTPHeader sets the header entries associated with key to the single element value. It replaces any existing values associated with key. The key is case insensitive; it is canonicalized by textproto.CanonicalMIMEHeaderKey.

type CallResourceResponse

type CallResourceResponse struct {
	// Status the HTTP response status.
	Status int

	// Headers the HTTP response headers.
	Headers map[string][]string

	// Body the HTTP response body.
	Body []byte
}

CallResourceResponse represents a response from a resource call.

type CallResourceResponseSender

type CallResourceResponseSender interface {
	Send(*CallResourceResponse) error
}

CallResourceResponseSender is used for sending resource call responses.

type CheckHealthHandler

type CheckHealthHandler interface {
	CheckHealth(ctx context.Context, req *CheckHealthRequest) (*CheckHealthResult, error)
}

CheckHealthHandler enables users to send health check requests to a backend plugin

type CheckHealthHandlerFunc

type CheckHealthHandlerFunc func(ctx context.Context, req *CheckHealthRequest) (*CheckHealthResult, error)

CheckHealthHandlerFunc is an adapter to allow the use of ordinary functions as backend.CheckHealthHandler. If f is a function with the appropriate signature, CheckHealthHandlerFunc(f) is a Handler that calls f.

func (CheckHealthHandlerFunc) CheckHealth

CheckHealth calls fn(ctx, req).

type CheckHealthRequest

type CheckHealthRequest struct {
	// PluginContext the contextual information for the request.
	PluginContext PluginContext

	// Headers the environment/metadata information for the request.
	//
	// To access forwarded HTTP headers please use
	// GetHTTPHeaders or GetHTTPHeader.
	Headers map[string]string
}

CheckHealthRequest contains the healthcheck request

func (*CheckHealthRequest) DeleteHTTPHeader

func (req *CheckHealthRequest) DeleteHTTPHeader(key string)

DeleteHTTPHeader deletes the values associated with key. The key is case insensitive; it is canonicalized by CanonicalHeaderKey.

func (*CheckHealthRequest) GetHTTPHeader

func (req *CheckHealthRequest) GetHTTPHeader(key string) string

GetHTTPHeader gets the first value associated with the given key. If there are no values associated with the key, Get returns "". It is case insensitive; textproto.CanonicalMIMEHeaderKey is used to canonicalize the provided key. Get assumes that all keys are stored in canonical form.

func (*CheckHealthRequest) GetHTTPHeaders

func (req *CheckHealthRequest) GetHTTPHeaders() http.Header

GetHTTPHeaders returns HTTP headers.

func (*CheckHealthRequest) SetHTTPHeader

func (req *CheckHealthRequest) SetHTTPHeader(key, value string)

SetHTTPHeader sets the header entries associated with key to the single element value. It replaces any existing values associated with key. The key is case insensitive; it is canonicalized by textproto.CanonicalMIMEHeaderKey.

type CheckHealthResult

type CheckHealthResult struct {
	// Status the HealthStatus of the healthcheck.
	Status HealthStatus

	// Message the message of the healthcheck, if any.
	Message string

	// JSONDetails the details of the healthcheck, if any, encoded as JSON bytes.
	JSONDetails []byte
}

CheckHealthResult contains the healthcheck response

type CollectMetricsHandler

type CollectMetricsHandler interface {
	CollectMetrics(ctx context.Context, req *CollectMetricsRequest) (*CollectMetricsResult, error)
}

CollectMetricsHandler handles metric collection.

type CollectMetricsHandlerFunc

type CollectMetricsHandlerFunc func(ctx context.Context, req *CollectMetricsRequest) (*CollectMetricsResult, error)

CollectMetricsHandlerFunc is an adapter to allow the use of ordinary functions as backend.CollectMetricsHandler. If f is a function with the appropriate signature, CollectMetricsHandlerFunc(f) is a Handler that calls f.

func (CollectMetricsHandlerFunc) CollectMetrics

CollectMetrics calls fn(ctx, req).

type CollectMetricsRequest

type CollectMetricsRequest struct {
	// PluginContext the contextual information for the request.
	PluginContext PluginContext
}

CollectMetricsRequest contains the metrics request

type CollectMetricsResult

type CollectMetricsResult struct {
	// PrometheusMetrics the Prometheus metrics encoded as bytes.
	PrometheusMetrics []byte
}

CollectMetricsResult collect metrics result.

type ConvertFromProtobuf

type ConvertFromProtobuf struct{}

ConvertFromProtobuf has a collection of methods for converting from the autogenerated protobuf go code to our SDK objects. This object exists to attach a collection of conversion methods to.

This is used internally by the SDK and inside Grafarg-server, plugin authors should not need this functionality.

func FromProto

func FromProto() ConvertFromProtobuf

FromProto returns a new ConvertFromProtobuf.

func (ConvertFromProtobuf) AppInstanceSettings

AppInstanceSettings converts protobuf version of an AppInstanceSettings to the SDK version.

func (ConvertFromProtobuf) CallResourceRequest

func (f ConvertFromProtobuf) CallResourceRequest(protoReq *pluginv2.CallResourceRequest) *CallResourceRequest

CallResourceRequest converts protobuf version of a CallResourceRequest to the SDK version.

func (ConvertFromProtobuf) CallResourceResponse

func (f ConvertFromProtobuf) CallResourceResponse(protoResp *pluginv2.CallResourceResponse) *CallResourceResponse

CallResourceResponse converts protobuf version of a CallResourceResponse to the SDK version.

func (ConvertFromProtobuf) CheckHealthRequest

func (f ConvertFromProtobuf) CheckHealthRequest(protoReq *pluginv2.CheckHealthRequest) *CheckHealthRequest

CheckHealthRequest converts protobuf version of a CheckHealthRequest to the SDK version.

func (ConvertFromProtobuf) CheckHealthResponse

func (f ConvertFromProtobuf) CheckHealthResponse(protoResp *pluginv2.CheckHealthResponse) *CheckHealthResult

CheckHealthResponse converts protobuf version of a HealthCheckResponse to the SDK version.

func (ConvertFromProtobuf) CollectMetricsRequest

func (f ConvertFromProtobuf) CollectMetricsRequest(protoReq *pluginv2.CollectMetricsRequest) *CollectMetricsRequest

CollectMetricsRequest converts protobuf version of a CollectMetricsRequest to the SDK version.

func (ConvertFromProtobuf) CollectMetricsResponse

func (f ConvertFromProtobuf) CollectMetricsResponse(protoResp *pluginv2.CollectMetricsResponse) *CollectMetricsResult

CollectMetricsResponse converts protobuf version of a CollectMetricsResponse to the SDK version.

func (ConvertFromProtobuf) DataQuery

func (f ConvertFromProtobuf) DataQuery(proto *pluginv2.DataQuery) *DataQuery

DataQuery converts protobuf version of a DataQuery to the SDK version.

func (ConvertFromProtobuf) DataSourceInstanceSettings

func (f ConvertFromProtobuf) DataSourceInstanceSettings(proto *pluginv2.DataSourceInstanceSettings, pluginID string) *DataSourceInstanceSettings

DataSourceInstanceSettings converts protobuf version of a DataSourceInstanceSettings to the SDK version.

func (ConvertFromProtobuf) GrafargConfig

func (f ConvertFromProtobuf) GrafargConfig(cfg map[string]string) *GrafargCfg

func (ConvertFromProtobuf) PluginContext

func (f ConvertFromProtobuf) PluginContext(proto *pluginv2.PluginContext) PluginContext

PluginContext converts protobuf version of a PluginContext to the SDK version.

func (ConvertFromProtobuf) PublishStreamRequest

func (f ConvertFromProtobuf) PublishStreamRequest(protoReq *pluginv2.PublishStreamRequest) *PublishStreamRequest

PublishStreamRequest ...

func (ConvertFromProtobuf) PublishStreamResponse

func (f ConvertFromProtobuf) PublishStreamResponse(protoReq *pluginv2.PublishStreamResponse) *PublishStreamResponse

PublishStreamResponse ...

func (ConvertFromProtobuf) QueryDataRequest

func (f ConvertFromProtobuf) QueryDataRequest(protoReq *pluginv2.QueryDataRequest) *QueryDataRequest

QueryDataRequest converts protobuf version of a QueryDataRequest to the SDK version.

func (ConvertFromProtobuf) QueryDataResponse

func (f ConvertFromProtobuf) QueryDataResponse(protoRes *pluginv2.QueryDataResponse) (*QueryDataResponse, error)

QueryDataResponse converts protobuf version of a QueryDataResponse to the SDK version.

func (ConvertFromProtobuf) RunStreamRequest

func (f ConvertFromProtobuf) RunStreamRequest(protoReq *pluginv2.RunStreamRequest) *RunStreamRequest

RunStreamRequest ...

func (ConvertFromProtobuf) StreamPacket

func (f ConvertFromProtobuf) StreamPacket(protoReq *pluginv2.StreamPacket) *StreamPacket

StreamPacket ...

func (ConvertFromProtobuf) SubscribeStreamRequest

func (f ConvertFromProtobuf) SubscribeStreamRequest(protoReq *pluginv2.SubscribeStreamRequest) *SubscribeStreamRequest

SubscribeStreamRequest ...

func (ConvertFromProtobuf) SubscribeStreamResponse

func (f ConvertFromProtobuf) SubscribeStreamResponse(protoReq *pluginv2.SubscribeStreamResponse) *SubscribeStreamResponse

SubscribeStreamResponse ...

func (ConvertFromProtobuf) TimeRange

func (f ConvertFromProtobuf) TimeRange(proto *pluginv2.TimeRange) TimeRange

TimeRange converts protobuf version of a TimeRange to the SDK version.

func (ConvertFromProtobuf) User

func (f ConvertFromProtobuf) User(user *pluginv2.User) *User

User converts protobuf version of a User to the SDK version.

func (ConvertFromProtobuf) UserAgent

UserAgent converts protobuf version of a UserAgent to the SDK version.

type ConvertToProtobuf

type ConvertToProtobuf struct{}

ConvertToProtobuf has a collection of methods for converting the autogenerated protobuf go code to our SDK objects. This object exists to attach a collection of conversion methods to.

This is used internally by the SDK and inside Grafarg-server, plugin authors should not need this functionality.

func ToProto

func ToProto() ConvertToProtobuf

ToProto returns a new ConvertToProtobuf.

func (ConvertToProtobuf) AppInstanceSettings

AppInstanceSettings converts the SDK version of an AppInstanceSettings to the protobuf version.

func (ConvertToProtobuf) CallResourceRequest

CallResourceRequest converts the SDK version of a CallResourceRequest to the protobuf version.

func (ConvertToProtobuf) CallResourceResponse

CallResourceResponse converts the SDK version of a CallResourceResponse to the protobuf version.

func (ConvertToProtobuf) CheckHealthResponse

func (t ConvertToProtobuf) CheckHealthResponse(res *CheckHealthResult) *pluginv2.CheckHealthResponse

CheckHealthResponse converts the SDK version of a CheckHealthResponse to the protobuf version.

func (ConvertToProtobuf) CollectMetricsRequest

CollectMetricsRequest converts the SDK version of a CollectMetricsRequest to the protobuf version.

func (ConvertToProtobuf) CollectMetricsResult

CollectMetricsResult converts the SDK version of a CollectMetricsResult to the protobuf version.

func (ConvertToProtobuf) DataQuery

DataQuery converts the SDK version of a DataQuery to the protobuf version.

func (ConvertToProtobuf) DataSourceInstanceSettings

DataSourceInstanceSettings converts the SDK version of a DataSourceInstanceSettings to the protobuf version.

func (ConvertToProtobuf) GrafargConfig

func (t ConvertToProtobuf) GrafargConfig(cfg *GrafargCfg) map[string]string

GrafargConfig converts the SDK version of a GrafargCfg to the protobuf version.

func (ConvertToProtobuf) HealthStatus

HealthStatus converts the SDK version of a HealthStatus to the protobuf version.

func (ConvertToProtobuf) PluginContext

func (t ConvertToProtobuf) PluginContext(pluginCtx PluginContext) *pluginv2.PluginContext

PluginContext converts the SDK version of a PluginContext to the protobuf version.

func (ConvertToProtobuf) PublishStreamRequest

PublishStreamRequest ...

func (ConvertToProtobuf) PublishStreamResponse

PublishStreamResponse ...

func (ConvertToProtobuf) QueryDataRequest

func (t ConvertToProtobuf) QueryDataRequest(req *QueryDataRequest) *pluginv2.QueryDataRequest

QueryDataRequest converts the SDK version of a QueryDataRequest to the protobuf version.

func (ConvertToProtobuf) QueryDataResponse

func (t ConvertToProtobuf) QueryDataResponse(res *QueryDataResponse) (*pluginv2.QueryDataResponse, error)

QueryDataResponse converts the SDK version of a QueryDataResponse to the protobuf version. It will set the RefID on the frames to the RefID key in Responses if a Frame's RefId property is an empty string.

func (ConvertToProtobuf) RunStreamRequest

func (t ConvertToProtobuf) RunStreamRequest(req *RunStreamRequest) *pluginv2.RunStreamRequest

RunStreamRequest ...

func (ConvertToProtobuf) StreamPacket

StreamPacket ...

func (ConvertToProtobuf) SubscribeStreamRequest

SubscribeStreamRequest ...

func (ConvertToProtobuf) SubscribeStreamResponse

SubscribeStreamResponse ...

func (ConvertToProtobuf) TimeRange

func (t ConvertToProtobuf) TimeRange(tr TimeRange) *pluginv2.TimeRange

TimeRange converts the SDK version of a TimeRange to the protobuf version.

func (ConvertToProtobuf) User

func (t ConvertToProtobuf) User(user *User) *pluginv2.User

User converts the SDK version of a User to the protobuf version.

func (ConvertToProtobuf) UserAgent

func (t ConvertToProtobuf) UserAgent(ua *useragent.UserAgent) string

UserAgent converts the SDK version of a useragent.UserAgent to the protobuf version.

type DataQuery

type DataQuery struct {
	// RefID is the unique identifier of the query, set by the frontend call.
	RefID string

	// QueryType is an optional identifier for the type of query.
	// It can be used to distinguish different types of queries.
	QueryType string

	// MaxDataPoints is the maximum number of datapoints that should be returned from a time series query.
	MaxDataPoints int64

	// Interval is the suggested duration between time points in a time series query.
	Interval time.Duration

	// TimeRange is the Start and End of the query as sent by the frontend.
	TimeRange TimeRange

	// JSON is the raw JSON query and includes the above properties as well as custom properties.
	JSON json.RawMessage
}

DataQuery represents a single query as sent from the frontend. A slice of DataQuery makes up the Queries property of a QueryDataRequest.

type DataResponse

type DataResponse struct {
	// The data returned from the Query. Each Frame repeats the RefID.
	Frames data.Frames

	// Error is a property to be set if the corresponding DataQuery has an error.
	Error error

	// Status codes map to HTTP status values
	Status Status

	// ErrorSource is the the source of the error
	ErrorSource ErrorSource
}

DataResponse contains the results from a DataQuery. A map of RefIDs (unique query identifiers) to this type makes up the Responses property of a QueryDataResponse. The Error property is used to allow for partial success responses from the containing QueryDataResponse.

func ErrDataResponse

func ErrDataResponse(status Status, message string) DataResponse

ErrDataResponse returns an error DataResponse given status and message.

func ErrDataResponseWithSource

func ErrDataResponseWithSource(status Status, src ErrorSource, message string) DataResponse

ErrDataResponseWithSource returns an error DataResponse given status, source of the error and message.

func FrameResponse

func FrameResponse(f data.Framer) *DataResponse

FrameResponse creates a DataResponse that contains the Framer's data.Frames.

func FrameResponseWithError

func FrameResponseWithError(f data.Framer, err error) *DataResponse

FrameResponseWithError creates a DataResponse with the error's contents (if not nil), and the Framer's data.Frames. This function is particularly useful if you have a function that returns `(StructX, error)`, where StructX implements Framer, which is a very common pattern.

func FrameResponseWithErrorAndSource

func FrameResponseWithErrorAndSource(f data.Framer, err error, source ErrorSource) *DataResponse

FrameResponseWithErrorAndSource creates a DataResponse with the error's contents (if not nil), and the Framer's data.Frames, and the source of the error. This function is particularly useful if you have a function that returns `(StructX, error)`, where StructX implements Framer, which is a very common pattern.

func (DataResponse) MarshalJSON

func (r DataResponse) MarshalJSON() ([]byte, error)

MarshalJSON writes the results as json

type DataSourceInstanceSettings

type DataSourceInstanceSettings struct {
	// ID is the Grafarg assigned numeric identifier of the the data source instance.
	ID int64

	// UID is the Grafarg assigned string identifier of the the data source instance.
	UID string

	// Type is the unique identifier of the plugin that the request is for.
	// This should be the same value as PluginContext.PluginId.
	Type string

	// Name is the configured name of the data source instance.
	Name string

	// URL is the configured URL of a data source instance (e.g. the URL of an API endpoint).
	URL string

	// User is a configured user for a data source instance. This is not a Grafarg user, rather an arbitrary string.
	User string

	// Database is the configured database for a data source instance.
	// Only used by Elasticsearch and Influxdb.
	// Please use JSONData to store information related to database.
	Database string

	// BasicAuthEnabled indicates if this data source instance should use basic authentication.
	BasicAuthEnabled bool

	// BasicAuthUser is the configured user for basic authentication. (e.g. when a data source uses basic
	// authentication to connect to whatever API it fetches data from).
	BasicAuthUser string

	// JSONData contains the raw DataSourceConfig as JSON as stored by Grafarg server. It repeats the properties in
	// this object and includes custom properties.
	JSONData json.RawMessage

	// DecryptedSecureJSONData contains key,value pairs where the encrypted configuration in Grafarg server have been
	// decrypted before passing them to the plugin.
	DecryptedSecureJSONData map[string]string

	// Updated is the last time the configuration for the data source instance was updated.
	Updated time.Time
}

DataSourceInstanceSettings represents settings for a data source instance.

In Grafarg a data source instance is a data source plugin of certain type that have been configured and created in a Grafarg organization.

func (*DataSourceInstanceSettings) HTTPClientOptions

func (s *DataSourceInstanceSettings) HTTPClientOptions(ctx context.Context) (httpclient.Options, error)

HTTPClientOptions creates httpclient.Options based on settings.

func (*DataSourceInstanceSettings) ProxyOptions

func (s *DataSourceInstanceSettings) ProxyOptions(clientCfg *proxy.ClientCfg) (*proxy.Options, error)

type ErrorSource

type ErrorSource string

ErrorSource type defines the source of the error

const (
	ErrorSourcePlugin     ErrorSource = "plugin"
	ErrorSourceDownstream ErrorSource = "downstream"
)

func ErrorSourceFromHTTPStatus

func ErrorSourceFromHTTPStatus(statusCode int) ErrorSource

ErrorSourceFromStatus returns an ErrorSource based on provided HTTP status code.

type FeatureToggles

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

func (FeatureToggles) IsEnabled

func (ft FeatureToggles) IsEnabled(f string) bool

IsEnabled returns true if feature f is contained in ft.enabled.

type ForwardHTTPHeaders

type ForwardHTTPHeaders interface {
	// SetHTTPHeader sets the header entries associated with key to the
	// single element value. It replaces any existing values
	// associated with key. The key is case insensitive; it is
	// canonicalized by textproto.CanonicalMIMEHeaderKey.
	SetHTTPHeader(key, value string)

	// DeleteHTTPHeader deletes the values associated with key.
	// The key is case insensitive; it is canonicalized by
	// CanonicalHeaderKey.
	DeleteHTTPHeader(key string)

	// GetHTTPHeader gets the first value associated with the given key. If
	// there are no values associated with the key, Get returns "".
	// It is case insensitive; textproto.CanonicalMIMEHeaderKey is
	// used to canonicalize the provided key. Get assumes that all
	// keys are stored in canonical form.
	GetHTTPHeader(key string) string

	// GetHTTPHeaders returns HTTP headers.
	GetHTTPHeaders() http.Header
}

ForwardHTTPHeaders interface marking that forward of HTTP headers is supported.

type GRPCSettings

type GRPCSettings struct {
	// MaxReceiveMsgSize the max gRPC message size in bytes the plugin can receive.
	// If this is <= 0, gRPC uses the default 16MB.
	MaxReceiveMsgSize int

	// MaxSendMsgSize the max gRPC message size in bytes the plugin can send.
	// If this is <= 0, gRPC uses the default `math.MaxInt32`.
	MaxSendMsgSize int
}

GRPCSettings settings for gRPC.

type GrafargCfg

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

func GrafargConfigFromContext

func GrafargConfigFromContext(ctx context.Context) *GrafargCfg

GrafargConfigFromContext returns Grafarg config from context.

func NewGrafargCfg

func NewGrafargCfg(cfg map[string]string) *GrafargCfg

func (*GrafargCfg) AppURL

func (c *GrafargCfg) AppURL() (string, error)

func (*GrafargCfg) Equal

func (c *GrafargCfg) Equal(c2 *GrafargCfg) bool

func (*GrafargCfg) FeatureToggles

func (c *GrafargCfg) FeatureToggles() FeatureToggles

func (*GrafargCfg) Get

func (c *GrafargCfg) Get(key string) string

type HTTPSettings

type HTTPSettings struct {
	Access            string
	URL               string
	BasicAuthEnabled  bool
	BasicAuthUser     string
	BasicAuthPassword string
	Headers           map[string]string

	Timeout               time.Duration
	DialTimeout           time.Duration
	KeepAlive             time.Duration
	TLSHandshakeTimeout   time.Duration
	ExpectContinueTimeout time.Duration
	MaxConnsPerHost       int
	MaxIdleConns          int
	MaxIdleConnsPerHost   int
	IdleConnTimeout       time.Duration

	TLSClientAuth     bool
	TLSAuthWithCACert bool
	TLSSkipVerify     bool
	TLSServerName     string
	TLSCACert         string
	TLSClientCert     string
	TLSClientKey      string

	SigV4Auth          bool
	SigV4Region        string
	SigV4AssumeRoleARN string
	SigV4AuthType      string
	SigV4ExternalID    string
	SigV4Profile       string
	SigV4AccessKey     string
	SigV4SecretKey     string

	JSONData       map[string]interface{}
	SecureJSONData map[string]string
}

HTTPSettings is a convenient struct for holding decoded HTTP settings from jsonData and secureJSONData.

func (*HTTPSettings) HTTPClientOptions

func (s *HTTPSettings) HTTPClientOptions() httpclient.Options

HTTPClientOptions creates and returns httpclient.Options.

type HealthStatus

type HealthStatus int

HealthStatus is the status of the plugin.

const (
	// HealthStatusUnknown means the status of the plugin is unknown.
	HealthStatusUnknown HealthStatus = iota

	// HealthStatusOk means the status of the plugin is good.
	HealthStatusOk

	// HealthStatusError means the plugin is in an error state.
	HealthStatusError
)

func (HealthStatus) String

func (hs HealthStatus) String() string

String textual represntation of the status.

type InitialData

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

InitialData to send to a client upon a successful subscription to a channel.

func NewInitialData

func NewInitialData(data json.RawMessage) (*InitialData, error)

NewInitialData allows sending JSON on subscription

func NewInitialFrame

func NewInitialFrame(frame *data.Frame, include data.FrameInclude) (*InitialData, error)

NewInitialFrame allows creating frame as subscription InitialData.

func (*InitialData) Data

func (d *InitialData) Data() []byte

Data allows to get prepared bytes of initial data.

type PluginContext

type PluginContext struct {
	// OrgID is The Grafarg organization identifier the request originating from.
	OrgID int64

	// PluginID is the unique identifier of the plugin that the request is for.
	PluginID string

	// PluginVersion is the version of the plugin that the request is for.
	PluginVersion string

	// User is the Grafarg user making the request.
	//
	// Will not be provided if Grafarg backend initiated the request,
	// for example when request is coming from Grafarg Alerting.
	User *User

	// AppInstanceSettings is the configured app instance settings.
	//
	// In Grafarg an app instance is an app plugin of certain
	// type that have been configured and enabled in a Grafarg organization.
	//
	// Will only be set if request targeting an app instance.
	AppInstanceSettings *AppInstanceSettings

	// DataSourceConfig is the configured data source instance
	// settings.
	//
	// In Grafarg a data source instance is a data source plugin of certain
	// type that have been configured and created in a Grafarg organization.
	//
	// Will only be set if request targeting a data source instance.
	DataSourceInstanceSettings *DataSourceInstanceSettings

	// GrafargConfig is the configuration settings provided by Grafarg.
	GrafargConfig *GrafargCfg

	// UserAgent is the user agent of the Grafarg server that initiated the gRPC request.
	// Will only be set if request is made from Grafarg v10.2.0 or later.
	UserAgent *useragent.UserAgent
}

PluginContext holds contextual information about a plugin request, such as Grafarg organization, user and plugin instance settings.

type Proxy

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

type PublishStreamRequest

type PublishStreamRequest struct {
	PluginContext PluginContext
	Path          string
	Data          json.RawMessage
}

PublishStreamRequest is EXPERIMENTAL and is a subject to change till Grafarg 8.

type PublishStreamResponse

type PublishStreamResponse struct {
	Status PublishStreamStatus
	Data   json.RawMessage
}

PublishStreamResponse is EXPERIMENTAL and is a subject to change till Grafarg 8.

type PublishStreamStatus

type PublishStreamStatus int32

PublishStreamStatus is a status of publication response.

const (
	// PublishStreamStatusOK means publication is allowed.
	PublishStreamStatusOK PublishStreamStatus = 0
	// PublishStreamStatusNotFound means stream does not exist at all.
	PublishStreamStatusNotFound PublishStreamStatus = 1
	// PublishStreamStatusPermissionDenied means that user is not allowed to publish.
	PublishStreamStatusPermissionDenied PublishStreamStatus = 2
)

type QueryDataHandler

type QueryDataHandler interface {
	// QueryData handles multiple queries and returns multiple responses.
	// req contains the queries []DataQuery (where each query contains RefID as a unique identifier).
	// The QueryDataResponse contains a map of RefID to the response for each query, and each response
	// contains Frames ([]*Frame).
	//
	// The Frames' RefID property, when it is an empty string, will be automatically set to
	// the RefID in QueryDataResponse.Responses map. This is done before the QueryDataResponse is
	// sent to Grafarg. Therefore one does not need to be set that property on frames when using this method.
	QueryData(ctx context.Context, req *QueryDataRequest) (*QueryDataResponse, error)
}

QueryDataHandler handles data queries.

type QueryDataHandlerFunc

type QueryDataHandlerFunc func(ctx context.Context, req *QueryDataRequest) (*QueryDataResponse, error)

QueryDataHandlerFunc is an adapter to allow the use of ordinary functions as backend.QueryDataHandler. If f is a function with the appropriate signature, QueryDataHandlerFunc(f) is a Handler that calls f.

func (QueryDataHandlerFunc) QueryData

QueryData calls fn(ctx, req).

type QueryDataRequest

type QueryDataRequest struct {
	// PluginContext the contextual information for the request.
	PluginContext PluginContext

	// Headers the environment/metadata information for the request.
	//
	// To access forwarded HTTP headers please use
	// GetHTTPHeaders or GetHTTPHeader.
	Headers map[string]string

	// Queries the data queries for the request.
	Queries []DataQuery
}

QueryDataRequest contains a single request which contains multiple queries. It is the input type for a QueryData call.

func (*QueryDataRequest) DeleteHTTPHeader

func (req *QueryDataRequest) DeleteHTTPHeader(key string)

DeleteHTTPHeader deletes the values associated with key. The key is case insensitive; it is canonicalized by CanonicalHeaderKey.

func (*QueryDataRequest) GetHTTPHeader

func (req *QueryDataRequest) GetHTTPHeader(key string) string

GetHTTPHeader gets the first value associated with the given key. If there are no values associated with the key, Get returns "". It is case insensitive; textproto.CanonicalMIMEHeaderKey is used to canonicalize the provided key. Get assumes that all keys are stored in canonical form.

func (*QueryDataRequest) GetHTTPHeaders

func (req *QueryDataRequest) GetHTTPHeaders() http.Header

GetHTTPHeaders returns HTTP headers.

func (*QueryDataRequest) SetHTTPHeader

func (req *QueryDataRequest) SetHTTPHeader(key, value string)

SetHTTPHeader sets the header entries associated with key to the single element value. It replaces any existing values associated with key. The key is case insensitive; it is canonicalized by textproto.CanonicalMIMEHeaderKey.

type QueryDataResponse

type QueryDataResponse struct {
	// Responses is a map of RefIDs (Unique Query ID) to *DataResponse.
	Responses Responses
}

QueryDataResponse contains the results from a QueryDataRequest. It is the return type of a QueryData call.

func NewQueryDataResponse

func NewQueryDataResponse() *QueryDataResponse

NewQueryDataResponse returns a QueryDataResponse with the Responses property initialized.

func (QueryDataResponse) MarshalJSON

func (r QueryDataResponse) MarshalJSON() ([]byte, error)

MarshalJSON writes the results as json

func (*QueryDataResponse) UnmarshalJSON

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

UnmarshalJSON will read JSON into a QueryDataResponse

type Responses

type Responses map[string]DataResponse

Responses is a map of RefIDs (Unique Query ID) to DataResponses. The QueryData method the QueryDataHandler method will set the RefId property on the DataResponses' frames based on these RefIDs.

type RunStreamRequest

type RunStreamRequest struct {
	PluginContext PluginContext
	Path          string
	Data          json.RawMessage
}

RunStreamRequest is EXPERIMENTAL and is a subject to change till Grafarg 8.

type ServeOpts

type ServeOpts struct {
	// CheckHealthHandler handler for health checks.
	CheckHealthHandler CheckHealthHandler

	// CallResourceHandler handler for resource calls.
	// Optional to implement.
	CallResourceHandler CallResourceHandler

	// QueryDataHandler handler for data queries.
	// Required to implement if data source.
	QueryDataHandler QueryDataHandler

	// StreamHandler handler for streaming queries.
	// This is EXPERIMENTAL and is a subject to change till Grafarg 8.
	StreamHandler StreamHandler

	// GRPCSettings settings for gPRC.
	GRPCSettings GRPCSettings
}

ServeOpts options for serving plugins.

type Status

type Status int
const (
	// StatusUnknown implies an error that should be updated to contain
	// an accurate status code, as none has been provided.
	// HTTP status code 500.
	StatusUnknown Status = http.StatusInternalServerError

	// StatusOK means that the action was successful.
	// HTTP status code 200.
	StatusOK Status = http.StatusOK

	// StatusUnauthorized means that the data source does not recognize the
	// client's authentication, either because it has not been provided
	// or is invalid for the operation.
	// HTTP status code 401.
	StatusUnauthorized Status = http.StatusUnauthorized

	// StatusForbidden means that the data source refuses to perform the
	// requested action for the authenticated user.
	// HTTP status code 403.
	StatusForbidden Status = http.StatusForbidden

	// StatusNotFound means that the data source does not have any
	// corresponding document to return to the request.
	// HTTP status code 404.
	StatusNotFound Status = http.StatusNotFound

	// StatusTooManyRequests means that the client is rate limited
	// by the data source and should back-off before trying again.
	// HTTP status code 429.
	StatusTooManyRequests Status = http.StatusTooManyRequests

	// StatusBadRequest means that the data source was unable to parse the
	// parameters or payload for the request.
	// HTTP status code 400.
	StatusBadRequest Status = http.StatusBadRequest

	// StatusValidationFailed means that the data source was able to parse
	// the payload for the request, but it failed one or more validation
	// checks.
	// HTTP status code 400.
	StatusValidationFailed Status = http.StatusBadRequest

	// StatusInternal means that the data source acknowledges that there's
	// an error, but that there is nothing the client can do to fix it.
	// HTTP status code 500.
	StatusInternal Status = http.StatusInternalServerError

	// StatusNotImplemented means that the data source does not support the
	// requested action. Typically used during development of new
	// features.
	// HTTP status code 501.
	StatusNotImplemented Status = http.StatusNotImplemented

	// StatusTimeout means that the data source did not complete the request
	// within the required time and aborted the action.
	// HTTP status code 504.
	StatusTimeout Status = http.StatusGatewayTimeout

	// StatusBadGateway means that the data source, while acting as a gateway
	// or proxy, received an invalid response from downstream.
	// HTTP status code 502.
	StatusBadGateway Status = http.StatusBadGateway
)

func (Status) IsValid

func (s Status) IsValid() bool

func (Status) String

func (s Status) String() string

type StreamHandler

type StreamHandler interface {
	// SubscribeStream called when a user tries to subscribe to a plugin/datasource
	// managed channel path – thus plugin can check subscribe permissions and communicate
	// options with Grafarg Core. As soon as first subscriber joins channel RunStream
	// will be called.
	SubscribeStream(context.Context, *SubscribeStreamRequest) (*SubscribeStreamResponse, error)
	// PublishStream called when a user tries to publish to a plugin/datasource
	// managed channel path. Here plugin can check publish permissions and
	// modify publication data if required.
	PublishStream(context.Context, *PublishStreamRequest) (*PublishStreamResponse, error)
	// RunStream will be initiated by Grafarg to consume a stream. RunStream will be
	// called once for the first client successfully subscribed to a channel path.
	// When Grafarg detects that there are no longer any subscribers inside a channel,
	// the call will be terminated until next active subscriber appears. Call termination
	// can happen with a delay.
	RunStream(context.Context, *RunStreamRequest, *StreamSender) error
}

StreamHandler handles streams. This is EXPERIMENTAL and is a subject to change till Grafarg 8.

type StreamPacket

type StreamPacket struct {
	Data json.RawMessage
}

StreamPacket is EXPERIMENTAL and is a subject to change till Grafarg 8.

type StreamPacketSender

type StreamPacketSender interface {
	Send(*StreamPacket) error
}

StreamPacketSender is EXPERIMENTAL and is a subject to change till Grafarg 8.

type StreamSender

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

StreamSender allows sending data to a stream. StreamSender is EXPERIMENTAL and is a subject to change till Grafarg 8.

func NewStreamSender

func NewStreamSender(packetSender StreamPacketSender) *StreamSender

func (*StreamSender) SendBytes

func (s *StreamSender) SendBytes(data []byte) error

SendBytes allow sending arbitrary Bytes to a stream. When sending data.Frame prefer using SendFrame method. When sending an arbitrary raw JSON prefer using SendJSON method.

func (*StreamSender) SendFrame

func (s *StreamSender) SendFrame(frame *data.Frame, include data.FrameInclude) error

SendFrame allows sending data.Frame to a stream.

func (*StreamSender) SendJSON

func (s *StreamSender) SendJSON(data []byte) error

SendJSON allow sending arbitrary JSON to a stream. When sending data.Frame prefer using SendFrame method.

type SubscribeStreamRequest

type SubscribeStreamRequest struct {
	PluginContext PluginContext
	Path          string
	Data          json.RawMessage
}

SubscribeStreamRequest is EXPERIMENTAL and is a subject to change till Grafarg 8.

type SubscribeStreamResponse

type SubscribeStreamResponse struct {
	Status      SubscribeStreamStatus
	InitialData *InitialData
}

SubscribeStreamResponse is EXPERIMENTAL and is a subject to change till Grafarg 8.

type SubscribeStreamStatus

type SubscribeStreamStatus int32

SubscribeStreamStatus is a status of subscription response.

const (
	// SubscribeStreamStatusOK means subscription is allowed.
	SubscribeStreamStatusOK SubscribeStreamStatus = 0
	// SubscribeStreamStatusNotFound means stream does not exist at all.
	SubscribeStreamStatusNotFound SubscribeStreamStatus = 1
	// SubscribeStreamStatusPermissionDenied means that user is not allowed to subscribe.
	SubscribeStreamStatusPermissionDenied SubscribeStreamStatus = 2
)

type TimeRange

type TimeRange struct {
	// From is the start time of the query.
	From time.Time

	// To is the end time of the query.
	To time.Time
}

TimeRange represents a time range for a query and is a property of DataQuery.

func (TimeRange) Duration

func (tr TimeRange) Duration() time.Duration

Duration returns a time.Duration representing the amount of time between From and To.

type User

type User struct {
	Login string
	Name  string
	Email string
	Role  string
}

User represents a Grafarg user.

Directories

Path Synopsis
Package app provides utilities for creating and serving a app plugin over gRPC.
Package app provides utilities for creating and serving a app plugin over gRPC.
Package datasource provides utilities for creating and serving a data source plugin over gRPC.
Package datasource provides utilities for creating and serving a data source plugin over gRPC.
Package grpcplugin provides support for serving plugin over gRPC.
Package grpcplugin provides support for serving plugin over gRPC.
Package httpclient provides HTTP client and outgoing HTTP request middleware.
Package httpclient provides HTTP client and outgoing HTTP request middleware.
Package instancemgmt provides utilities for managing plugin instances.
Package instancemgmt provides utilities for managing plugin instances.
Package log provides a logging interface to send logs from plugins to Grafarg server.
Package log provides a logging interface to send logs from plugins to Grafarg server.
Package proxy provides utilities for updating a data source plugin connection to go through a proxy.
Package proxy provides utilities for updating a data source plugin connection to go through a proxy.
Package resource provides utils for handling resource calls.
Package resource provides utils for handling resource calls.
httpadapter
Package httpadapter provides support for handling resource calls using an http.Handler.
Package httpadapter provides support for handling resource calls using an http.Handler.

Jump to

Keyboard shortcuts

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