backend

package
v0.260.2 Latest Latest
Warning

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

Go to latest
Published: Dec 10, 2024 License: Apache-2.0 Imports: 53 Imported by: 431

Documentation

Overview

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

Index

Constants

View Source
const (
	AppURL                           = "GF_APP_URL"
	ConcurrentQueryCount             = "GF_CONCURRENT_QUERY_COUNT"
	UserFacingDefaultError           = "GF_USER_FACING_DEFAULT_ERROR"
	SQLRowLimit                      = "GF_SQL_ROW_LIMIT"
	SQLMaxOpenConnsDefault           = "GF_SQL_MAX_OPEN_CONNS_DEFAULT"
	SQLMaxIdleConnsDefault           = "GF_SQL_MAX_IDLE_CONNS_DEFAULT"
	SQLMaxConnLifetimeSecondsDefault = "GF_SQL_MAX_CONN_LIFETIME_SECONDS_DEFAULT"
	ResponseLimit                    = "GF_RESPONSE_LIMIT"
	AppClientSecret                  = "GF_PLUGIN_APP_CLIENT_SECRET" // nolint:gosec
)
View Source
const (
	// ErrorSourcePlugin error originates from plugin.
	ErrorSourcePlugin = status.SourcePlugin

	// ErrorSourceDownstream error originates from downstream service.
	ErrorSourceDownstream = status.SourceDownstream

	// DefaultErrorSource is the default [ErrorSource] that should be used when it is not explicitly set.
	DefaultErrorSource = status.SourcePlugin
)
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"

	// GrafanaUserSignInTokenHeaderName the header name used for forwarding
	// the SignIn token of a Grafana User.
	// Requires idForwarded feature toggle enabled.
	GrafanaUserSignInTokenHeaderName = "X-Grafana-Id" //nolint:gosec // this is not a hardcoded credential

	// 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 used 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 used to specify a pprof port (default 6060).
	PluginProfilingPortEnv = "GF_PLUGIN_PROFILING_PORT" // nolint:gosec

	// PluginProfilingBlockRateEnv is a constant for the GF_PLUGIN_PROFILING_BLOCK_RATE environment
	// variable used to control the fraction of goroutine blocking events that are reported in the
	// blocking profile, default `0` (i.e. track no events). Using `5` would report 20% of all events.
	PluginProfilingBlockRateEnv = "GF_PLUGIN_PROFILING_BLOCK_RATE" // nolint:gosec

	// PluginProfilingMutexRateEnv is a constant for the GF_PLUGIN_PROFILING_MUTEX_RATE environment
	// variable used to Controls the fraction of mutex contention events that are reported in the
	// mutex profile, default `0` (i.e. track no events). Using `5` would report 20% of all events.
	PluginProfilingMutexRateEnv = "GF_PLUGIN_PROFILING_MUTEX_RATE" // 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"
)

Variables

Logger is the default logger instance. This can be used directly to log from your plugin to grafana-server with calls like 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 AppInstanceSettingsToProtoBytes added in v0.232.0

func AppInstanceSettingsToProtoBytes(s *AppInstanceSettings) ([]byte, error)

func DataSourceInstanceSettingsToProtoBytes added in v0.232.0

func DataSourceInstanceSettingsToProtoBytes(s *DataSourceInstanceSettings) ([]byte, error)

func DownstreamError added in v0.240.0

func DownstreamError(err error) error

DownstreamError creates a new error with status ErrorSourceDownstream.

func DownstreamErrorf added in v0.240.0

func DownstreamErrorf(format string, a ...any) error

DownstreamErrorf creates a new error with status ErrorSourceDownstream and formats according to a format specifier and returns the string as a value that satisfies error.

func GRPCServeOpts added in v0.224.0

func GRPCServeOpts(opts ServeOpts) (grpcplugin.ServeOpts, error)

func GracefulStandaloneServe added in v0.156.0

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 IsDownstreamError added in v0.240.0

func IsDownstreamError(err error) bool

IsDownstreamError return true if provided error is an error with downstream source or a timeout error or a cancelled error.

func IsDownstreamHTTPError added in v0.253.0

func IsDownstreamHTTPError(err error) bool

IsDownstreamError return true if provided error is an error with downstream source or a HTTP timeout error or a cancelled error or a connection reset/refused error or dns not found error.

func JSONDataFromHTTPClientOptions added in v0.109.0

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

JSONDataFromHTTPClientOptions extracts JSON data from CustomOptions of httpclient.Options.

func Manage added in v0.156.0

func Manage(pluginID string, serveOpts ServeOpts) error

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

func PluginError added in v0.260.0

func PluginError(err error) error

PluginError creates a new error with status ErrorSourcePlugin.

func SecureJSONDataFromHTTPClientOptions added in v0.109.0

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

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

func Serve deprecated

func Serve(opts ServeOpts) error

Serve starts serving the plugin over gRPC.

Deprecated: Serve exists for historical compatibility and might be removed in a future version. Please migrate to use Manage instead.

func SetupPluginEnvironment added in v0.29.0

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 added in v0.157.0

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

SetupTracer sets up the global OTEL trace provider and tracer.

func TestStandaloneServe added in v0.167.0

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 added in v0.194.0

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

UserAgentFromContext returns user agent from context.

func WithDownstreamErrorSource added in v0.240.0

func WithDownstreamErrorSource(ctx context.Context) error

WithDownstreamErrorSource mutates the provided context by setting the error source to ErrorSourceDownstream. If the provided context does not have a error source, the context will not be mutated and an error returned. This means that [initErrorSource] has to be called before this function.

func WithEndpoint added in v0.237.0

func WithEndpoint(ctx context.Context, endpoint Endpoint) context.Context

WithEndpoint adds endpoint to ctx.

func WithErrorSource added in v0.240.0

func WithErrorSource(ctx context.Context, s ErrorSource) error

WithErrorSource mutates the provided context by setting the error source to s. If the provided context does not have a error source, the context will not be mutated and an error returned. This means that [initErrorSource] has to be called before this function.

func WithGrafanaConfig added in v0.182.0

func WithGrafanaConfig(ctx context.Context, cfg *GrafanaCfg) context.Context

WithGrafanaConfig injects supplied Grafana config into context.

func WithPluginContext added in v0.237.0

func WithPluginContext(ctx context.Context, pluginCtx PluginContext) context.Context

WithPluginContext adds pluginCtx to ctx.

Note: Used internally by SDK so you normally don't need to use/call this, unless in tests and such.

func WithTenant added in v0.221.0

func WithTenant(ctx context.Context, tenantID string) context.Context

WithTenant injects supplied tenant ID into context.

func WithUser added in v0.237.0

func WithUser(ctx context.Context, user *User) context.Context

WithPluginContext adds user to ctx.

Note: Used internally by SDK so you normally don't need to use/call this, unless in tests and such.

func WithUserAgent added in v0.194.0

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

WithUserAgent injects supplied user agent into context.

Types

type AdmissionHandler added in v0.232.0

type AdmissionHandler interface {
	// ValidateAdmission is a simple yes|no check if an object can be saved
	ValidateAdmission(context.Context, *AdmissionRequest) (*ValidationResponse, error)
	// MutateAdmission converts the input into an object that can be saved, or rejects the request
	MutateAdmission(context.Context, *AdmissionRequest) (*MutationResponse, error)
}

AdmissionHandler is an EXPERIMENTAL service that allows checking objects before they are saved This is modeled after the kubernetes model for admission controllers Since grafana 11.1, this feature is under active development and will continue to evolve in 2024 This may also be replaced with a more native kubernetes solution that does not work with existing tooling

type AdmissionRequest added in v0.232.0

type AdmissionRequest struct {
	// NOTE: this may not include populated instance settings depending on the request
	PluginContext PluginContext `json:"pluginContext,omitempty"`
	// The requested operation
	Operation AdmissionRequestOperation `json:"operation,omitempty"`
	// The object kind
	Kind GroupVersionKind `json:"kind,omitempty"`
	// Object is the object in the request.  This includes the full metadata envelope.
	ObjectBytes []byte `json:"object_bytes,omitempty"`
	// OldObject is the object as it currently exists in storage. This includes the full metadata envelope.
	OldObjectBytes []byte `json:"old_object_bytes,omitempty"`
}

type AdmissionRequestOperation added in v0.232.0

type AdmissionRequestOperation int32

Operation is the type of resource operation being checked for admission control https://github.com/kubernetes/kubernetes/blob/v1.30.0/pkg/apis/admission/types.go#L158

const (
	AdmissionRequestCreate AdmissionRequestOperation = 0
	AdmissionRequestUpdate AdmissionRequestOperation = 1
	AdmissionRequestDelete AdmissionRequestOperation = 2
)

func (AdmissionRequestOperation) String added in v0.232.0

func (o AdmissionRequestOperation) String() string

String textual representation of the operation.

type AppInstanceSettings added in v0.54.0

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 Grafana
	// 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

	// The API Version when settings were saved
	// NOTE: this may be older than the current version
	APIVersion string
}

AppInstanceSettings represents settings for an app instance.

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

func AppInstanceSettingsFromProto added in v0.232.0

func AppInstanceSettingsFromProto(body []byte) (*AppInstanceSettings, error)

func (*AppInstanceSettings) GVK added in v0.232.0

func (*AppInstanceSettings) HTTPClientOptions added in v0.96.0

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

HTTPClientOptions creates httpclient.Options based on settings.

type BaseHandler added in v0.251.0

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

BaseHandler base handler provides a base implementation of Handler interface passing the request down the chain to next Handler. This allows handlers to avoid implementing the full Handler interface.

func NewBaseHandler added in v0.251.0

func NewBaseHandler(next Handler) BaseHandler

NewBaseHandler creates a new BaseHandler.

func (BaseHandler) CallResource added in v0.251.0

func (BaseHandler) CheckHealth added in v0.251.0

func (BaseHandler) CollectMetrics added in v0.251.0

func (*BaseHandler) ConvertObjects added in v0.251.0

func (m *BaseHandler) ConvertObjects(ctx context.Context, req *ConversionRequest) (*ConversionResponse, error)

func (*BaseHandler) MutateAdmission added in v0.251.0

func (m *BaseHandler) MutateAdmission(ctx context.Context, req *AdmissionRequest) (*MutationResponse, error)

func (BaseHandler) PublishStream added in v0.251.0

func (BaseHandler) QueryData added in v0.251.0

func (BaseHandler) RunStream added in v0.251.0

func (m BaseHandler) RunStream(ctx context.Context, req *RunStreamRequest, sender *StreamSender) error

func (BaseHandler) SubscribeStream added in v0.251.0

func (BaseHandler) ValidateAdmission added in v0.251.0

func (m BaseHandler) ValidateAdmission(ctx context.Context, req *AdmissionRequest) (*ValidationResponse, error)

type CallResourceHandler

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

CallResourceHandler handles resource calls.

type CallResourceHandlerFunc added in v0.61.0

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

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

func (CallResourceHandlerFunc) CallResource added in v0.61.0

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 added in v0.147.0

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 added in v0.147.0

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 added in v0.147.0

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

GetHTTPHeaders returns HTTP headers.

func (*CallResourceRequest) SetHTTPHeader added in v0.147.0

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 CallResourceResponseSenderFunc added in v0.237.0

type CallResourceResponseSenderFunc func(resp *CallResourceResponse) error

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

func (CallResourceResponseSenderFunc) Send added in v0.237.0

Send calls fn(resp).

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 added in v0.61.0

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

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

func (CheckHealthHandlerFunc) CheckHealth added in v0.61.0

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 added in v0.147.0

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 added in v0.147.0

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 added in v0.147.0

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

GetHTTPHeaders returns HTTP headers.

func (*CheckHealthRequest) SetHTTPHeader added in v0.147.0

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 added in v0.67.0

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

CollectMetricsHandler handles metric collection.

type CollectMetricsHandlerFunc added in v0.67.0

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 added in v0.67.0

CollectMetrics calls fn(ctx, req).

type CollectMetricsRequest added in v0.126.0

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

CollectMetricsRequest contains the metrics request

type CollectMetricsResult added in v0.67.0

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

CollectMetricsResult collect metrics result.

type ConversionHandler added in v0.243.0

type ConversionHandler interface {
	// ConvertObject is called to covert objects between different versions
	ConvertObjects(context.Context, *ConversionRequest) (*ConversionResponse, error)
}

type ConversionRequest added in v0.232.0

type ConversionRequest struct {
	// NOTE: this may not include app or datasource instance settings depending on the request
	PluginContext PluginContext `json:"pluginContext,omitempty"`
	// UID is an identifier for the individual request/response. It allows distinguishing instances of requests which are
	// otherwise identical (parallel requests, etc).
	// The UID is meant to track the round trip (request/response) between the Kubernetes API server and the webhook, not the user request.
	// It is suitable for correlating log entries between the webhook and apiserver, for either auditing or debugging.
	UID string `json:"uid,omitempty"`
	// TargetVersion is the version the object should be converted to.
	TargetVersion GroupVersion `json:"target_version,omitempty"`
	// Objects is the list of objects to convert. This contains the full metadata envelope.
	Objects []RawObject `json:"objects,omitempty"`
}

ConversionRequest supports converting an object from on version to another

type ConversionResponse added in v0.232.0

type ConversionResponse struct {
	// UID is an identifier for the individual request/response.
	// This should be copied over from the corresponding `request.uid`.
	UID string `json:"uid,omitempty"`
	// Result contains extra details into why an admission request was denied.
	Result *StatusResult `json:"result,omitempty"`
	// Objects is the list of converted version of `request.objects` if the `result` is successful, otherwise empty.
	Objects []RawObject `json:"objects,omitempty"`
}

type ConvertFromProtobuf added in v0.54.0

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 Grafana-server, plugin authors should not need this functionality.

func FromProto added in v0.54.0

func FromProto() ConvertFromProtobuf

FromProto returns a new ConvertFromProtobuf.

func (ConvertFromProtobuf) AdmissionRequest added in v0.232.0

AdmissionRequest ...

func (ConvertFromProtobuf) AppInstanceSettings added in v0.54.0

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

func (ConvertFromProtobuf) CallResourceRequest added in v0.54.0

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

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

func (ConvertFromProtobuf) CallResourceResponse added in v0.67.0

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

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

func (ConvertFromProtobuf) CheckHealthRequest added in v0.67.0

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

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

func (ConvertFromProtobuf) CheckHealthResponse added in v0.67.0

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

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

func (ConvertFromProtobuf) CollectMetricsRequest added in v0.126.0

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

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

func (ConvertFromProtobuf) CollectMetricsResponse added in v0.67.0

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

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

func (ConvertFromProtobuf) ConversionRequest added in v0.232.0

ConversionRequest ...

func (ConvertFromProtobuf) ConversionResponse added in v0.232.0

ConversionResponse ...

func (ConvertFromProtobuf) DataQuery added in v0.54.0

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

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

func (ConvertFromProtobuf) DataSourceInstanceSettings added in v0.54.0

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

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

func (ConvertFromProtobuf) GrafanaConfig added in v0.177.0

func (f ConvertFromProtobuf) GrafanaConfig(cfg map[string]string) *GrafanaCfg

func (ConvertFromProtobuf) GroupVersion added in v0.243.0

GroupVersion ...

func (ConvertFromProtobuf) GroupVersionKind added in v0.232.0

GroupVersionKind ...

func (ConvertFromProtobuf) MutationResponse added in v0.232.0

MutationResponse ...

func (ConvertFromProtobuf) PluginContext added in v0.54.0

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

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

func (ConvertFromProtobuf) PublishStreamRequest added in v0.91.0

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

PublishStreamRequest ...

func (ConvertFromProtobuf) PublishStreamResponse added in v0.91.0

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

PublishStreamResponse ...

func (ConvertFromProtobuf) QueryDataRequest added in v0.54.0

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

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

func (ConvertFromProtobuf) QueryDataResponse added in v0.54.0

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

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

func (ConvertFromProtobuf) RawObject added in v0.243.0

func (f ConvertFromProtobuf) RawObject(req *pluginv2.RawObject) RawObject

RawObject ...

func (ConvertFromProtobuf) RawObjects added in v0.243.0

func (f ConvertFromProtobuf) RawObjects(req []*pluginv2.RawObject) []RawObject

RawObjects ...

func (ConvertFromProtobuf) RunStreamRequest added in v0.89.0

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

RunStreamRequest ...

func (ConvertFromProtobuf) StatusResult added in v0.232.0

StatusResult ...

func (ConvertFromProtobuf) StreamPacket added in v0.89.0

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

StreamPacket ...

func (ConvertFromProtobuf) SubscribeStreamRequest added in v0.91.0

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

SubscribeStreamRequest ...

func (ConvertFromProtobuf) SubscribeStreamResponse added in v0.91.0

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

SubscribeStreamResponse ...

func (ConvertFromProtobuf) TimeRange added in v0.54.0

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

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

func (ConvertFromProtobuf) User added in v0.54.0

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

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

func (ConvertFromProtobuf) UserAgent added in v0.177.0

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

func (ConvertFromProtobuf) ValidationResponse added in v0.232.0

ValidationResponse ...

type ConvertObjectsFunc added in v0.243.0

type ConvertObjectsFunc func(context.Context, *ConversionRequest) (*ConversionResponse, error)

func (ConvertObjectsFunc) ConvertObjects added in v0.249.0

ConvertObjects calls fn(ctx, req).

type ConvertQueryFunc added in v0.249.0

type ConvertQueryFunc func(ctx context.Context, req *QueryDataRequest) (*QueryConversionResponse, error)

func (ConvertQueryFunc) ConvertQueryDataRequest added in v0.249.0

func (fn ConvertQueryFunc) ConvertQueryDataRequest(ctx context.Context, req *QueryDataRequest) (*QueryConversionResponse, error)

type ConvertToProtobuf added in v0.54.0

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 Grafana-server, plugin authors should not need this functionality.

func ToProto added in v0.54.0

func ToProto() ConvertToProtobuf

ToProto returns a new ConvertToProtobuf.

func (ConvertToProtobuf) AdmissionRequest added in v0.232.0

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

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

func (ConvertToProtobuf) AppInstanceSettings added in v0.54.0

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

func (ConvertToProtobuf) CallResourceRequest added in v0.54.0

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

func (ConvertToProtobuf) CallResourceResponse added in v0.54.0

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

func (ConvertToProtobuf) CheckHealthResponse added in v0.54.0

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

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

func (ConvertToProtobuf) CollectMetricsRequest added in v0.126.0

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

func (ConvertToProtobuf) CollectMetricsResult added in v0.126.0

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

func (ConvertToProtobuf) ConversionRequest added in v0.232.0

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

func (ConvertToProtobuf) ConversionResponse added in v0.232.0

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

func (ConvertToProtobuf) DataQuery added in v0.54.0

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

func (ConvertToProtobuf) DataSourceInstanceSettings added in v0.54.0

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

func (ConvertToProtobuf) GrafanaConfig added in v0.177.0

func (t ConvertToProtobuf) GrafanaConfig(cfg *GrafanaCfg) map[string]string

GrafanaConfig converts the SDK version of a GrafanaCfg to the protobuf version.

func (ConvertToProtobuf) GroupVersion added in v0.243.0

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

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

func (ConvertToProtobuf) GroupVersionKind added in v0.232.0

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

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

func (ConvertToProtobuf) HealthStatus added in v0.54.0

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

func (ConvertToProtobuf) MutationResponse added in v0.232.0

func (t ConvertToProtobuf) MutationResponse(rsp *MutationResponse) *pluginv2.MutationResponse

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

func (ConvertToProtobuf) PluginContext added in v0.54.0

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

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

func (ConvertToProtobuf) PublishStreamRequest added in v0.91.0

PublishStreamRequest ...

func (ConvertToProtobuf) PublishStreamResponse added in v0.91.0

PublishStreamResponse ...

func (ConvertToProtobuf) QueryDataRequest added in v0.54.0

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

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

func (ConvertToProtobuf) QueryDataResponse added in v0.54.0

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) RawObject added in v0.243.0

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

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

func (ConvertToProtobuf) RawObjects added in v0.243.0

func (t ConvertToProtobuf) RawObjects(req []RawObject) []*pluginv2.RawObject

RawObjects converts the SDK version of a RawObject to the protobuf version.

func (ConvertToProtobuf) RunStreamRequest added in v0.89.0

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

RunStreamRequest ...

func (ConvertToProtobuf) StatusResult added in v0.232.0

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

func (ConvertToProtobuf) StreamPacket added in v0.89.0

StreamPacket ...

func (ConvertToProtobuf) SubscribeStreamRequest added in v0.91.0

SubscribeStreamRequest ...

func (ConvertToProtobuf) SubscribeStreamResponse added in v0.91.0

SubscribeStreamResponse ...

func (ConvertToProtobuf) TimeRange added in v0.54.0

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

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

func (ConvertToProtobuf) User added in v0.54.0

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

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

func (ConvertToProtobuf) UserAgent added in v0.177.0

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

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

func (ConvertToProtobuf) ValidationResponse added in v0.232.0

ValidationResponse converts the SDK version of a ValidationResponse 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 added in v0.35.0

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 added in v0.142.0

func ErrDataResponse(status Status, message string) DataResponse

ErrDataResponse returns an error DataResponse given status and message.

func ErrDataResponseWithSource added in v0.179.0

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

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

func ErrorResponseWithErrorSource added in v0.260.0

func ErrorResponseWithErrorSource(err error) DataResponse

Response returns an error DataResponse with error and source of the error if present. If the error does not have a source, it keeps the ErrorSource empty.

func FrameResponse added in v0.80.0

func FrameResponse(f data.Framer) *DataResponse

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

func FrameResponseWithError added in v0.80.0

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 added in v0.179.0

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) DeepCopy added in v0.213.0

func (r *DataResponse) DeepCopy() *DataResponse

func (DataResponse) MarshalJSON added in v0.90.0

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

MarshalJSON writes the results as json

type DataSourceInstanceSettings added in v0.54.0

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

	// UID is the Grafana 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 Grafana 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 Grafana 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 Grafana 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

	// The API Version when settings were saved
	// NOTE: this may be older than the current version
	APIVersion string
}

DataSourceInstanceSettings represents settings for a data source instance.

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

func DataSourceInstanceSettingsFromProto added in v0.232.0

func DataSourceInstanceSettingsFromProto(body []byte, pluginID string) (*DataSourceInstanceSettings, error)

func (*DataSourceInstanceSettings) GVK added in v0.232.0

func (*DataSourceInstanceSettings) HTTPClientOptions added in v0.96.0

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

HTTPClientOptions creates httpclient.Options based on settings.

func (*DataSourceInstanceSettings) ProxyClient added in v0.209.0

func (*DataSourceInstanceSettings) ProxyOptions added in v0.171.0

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

func (*DataSourceInstanceSettings) ProxyOptionsFromContext added in v0.223.0

func (s *DataSourceInstanceSettings) ProxyOptionsFromContext(ctx context.Context) (*proxy.Options, error)

type Endpoint added in v0.237.0

type Endpoint string

Endpoint used for defining names for endpoints/handlers.

const (
	// EndpointValidateAdmission friendly name for the validate admission endpoint/handler.
	EndpointValidateAdmission Endpoint = "validateAdmission"

	// EndpointMutateAdmission friendly name for the mutate admission endpoint/handler.
	EndpointMutateAdmission Endpoint = "mutateAdmission"
)
const (
	// EndpointCheckHealth friendly name for the check health endpoint/handler.
	EndpointCheckHealth Endpoint = "checkHealth"

	// EndpointCollectMetrics friendly name for the collect metrics endpoint/handler.
	EndpointCollectMetrics Endpoint = "collectMetrics"
)
const (
	// EndpointSubscribeStream friendly name for the subscribe stream endpoint/handler.
	EndpointSubscribeStream Endpoint = "subscribeStream"

	// EndpointPublishStream friendly name for the publish stream endpoint/handler.
	EndpointPublishStream Endpoint = "publishStream"

	// EndpointRunStream friendly name for the run stream endpoint/handler.
	EndpointRunStream Endpoint = "runStream"
)
const EndpointCallResource Endpoint = "callResource"

EndpointCallResource friendly name for the call resource endpoint/handler.

const (
	// EndpointConvertObjects friendly name for the convert objects endpoint/handler.
	EndpointConvertObjects Endpoint = "convertObjects"
)
const EndpointQueryData Endpoint = "queryData"

EndpointQueryData friendly name for the query data endpoint/handler.

func EndpointFromContext added in v0.237.0

func EndpointFromContext(ctx context.Context) Endpoint

EndpointFromContext extracts Endpoint from ctx if available, otherwise empty Endpoint.

func (Endpoint) IsEmpty added in v0.237.0

func (e Endpoint) IsEmpty() bool

IsEmpty returns true if endpoint is not set/empty string.

func (Endpoint) String added in v0.240.0

func (e Endpoint) String() string

type ErrorSource added in v0.179.0

type ErrorSource = status.Source

ErrorSource type defines the source of the error

func ErrorSourceFromContext added in v0.253.0

func ErrorSourceFromContext(ctx context.Context) ErrorSource

ErrorSourceFromContext returns the error source stored in the context. If no error source is stored in the context, DefaultErrorSource is returned.

func ErrorSourceFromHTTPStatus added in v0.180.0

func ErrorSourceFromHTTPStatus(statusCode int) ErrorSource

ErrorSourceFromHTTPStatus returns an ErrorSource based on provided HTTP status code.

type ErrorSourceMiddleware added in v0.253.0

type ErrorSourceMiddleware struct {
	BaseHandler
}

func (*ErrorSourceMiddleware) CallResource added in v0.253.0

func (*ErrorSourceMiddleware) CheckHealth added in v0.253.0

func (*ErrorSourceMiddleware) CollectMetrics added in v0.253.0

func (*ErrorSourceMiddleware) ConvertObjects added in v0.253.0

func (*ErrorSourceMiddleware) MutateAdmission added in v0.253.0

func (m *ErrorSourceMiddleware) MutateAdmission(ctx context.Context, req *AdmissionRequest) (*MutationResponse, error)

func (*ErrorSourceMiddleware) PublishStream added in v0.253.0

func (*ErrorSourceMiddleware) QueryData added in v0.253.0

func (*ErrorSourceMiddleware) RunStream added in v0.253.0

func (m *ErrorSourceMiddleware) RunStream(ctx context.Context, req *RunStreamRequest, sender *StreamSender) error

func (*ErrorSourceMiddleware) SubscribeStream added in v0.253.0

func (*ErrorSourceMiddleware) ValidateAdmission added in v0.253.0

func (m *ErrorSourceMiddleware) ValidateAdmission(ctx context.Context, req *AdmissionRequest) (*ValidationResponse, error)

type ErrorWithSource added in v0.260.0

type ErrorWithSource = status.ErrorWithSource

func NewErrorWithSource added in v0.260.0

func NewErrorWithSource(err error, source ErrorSource) ErrorWithSource

type FeatureToggles added in v0.177.0

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

func (FeatureToggles) IsEnabled added in v0.177.0

func (ft FeatureToggles) IsEnabled(f string) bool

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

type ForwardHTTPHeaders added in v0.147.0

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 added in v0.61.0

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 GrafanaCfg added in v0.177.0

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

func GrafanaConfigFromContext added in v0.177.0

func GrafanaConfigFromContext(ctx context.Context) *GrafanaCfg

GrafanaConfigFromContext returns Grafana config from context.

func NewGrafanaCfg added in v0.177.0

func NewGrafanaCfg(cfg map[string]string) *GrafanaCfg

func (*GrafanaCfg) AppURL added in v0.189.0

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

func (*GrafanaCfg) ConcurrentQueryCount added in v0.202.0

func (c *GrafanaCfg) ConcurrentQueryCount() (int, error)

func (*GrafanaCfg) Equal added in v0.177.0

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

func (*GrafanaCfg) FeatureToggles added in v0.177.0

func (c *GrafanaCfg) FeatureToggles() FeatureToggles

func (*GrafanaCfg) Get added in v0.177.0

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

func (*GrafanaCfg) PluginAppClientSecret added in v0.219.0

func (c *GrafanaCfg) PluginAppClientSecret() (string, error)

func (*GrafanaCfg) ProxyHash added in v0.259.3

func (c *GrafanaCfg) ProxyHash() string

ProxyHash returns the last four characters of the base64-encoded PDC client key contents, if present, for use in datasource instance caching. The contents should be PEM-encoded, so we try to PEM-decode them, and, if successful, return the base-64 encoding of the final three bytes, giving a four character hash.

func (*GrafanaCfg) ResponseLimit added in v0.215.0

func (c *GrafanaCfg) ResponseLimit() int64

func (*GrafanaCfg) SQL added in v0.212.0

func (c *GrafanaCfg) SQL() (SQLConfig, error)

func (*GrafanaCfg) UserFacingDefaultError added in v0.212.0

func (c *GrafanaCfg) UserFacingDefaultError() (string, error)

type GroupVersion added in v0.243.0

type GroupVersion struct {
	Group   string `json:"group,omitempty"`
	Version string `json:"version,omitempty"`
}

type GroupVersionKind added in v0.232.0

type GroupVersionKind struct {
	Group   string `json:"group,omitempty"`
	Version string `json:"version,omitempty"`
	Kind    string `json:"kind,omitempty"`
}

Identify the Object properties

type HTTPSettings added in v0.96.0

type HTTPSettings struct {
	Access            string
	URL               string
	BasicAuthEnabled  bool
	BasicAuthUser     string
	BasicAuthPassword string
	Header            http.Header

	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 added in v0.96.0

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

HTTPClientOptions creates and returns httpclient.Options.

type Handler added in v0.251.0

Handler interface for all handlers.

type HandlerMiddleware added in v0.251.0

type HandlerMiddleware interface {
	// CreateHandlerMiddleware creates a new Handler by decorating next Handler.
	CreateHandlerMiddleware(next Handler) Handler
}

HandlerMiddleware is an interface representing the ability to create a middleware that implements the Handler interface.

func NewErrorSourceMiddleware added in v0.253.0

func NewErrorSourceMiddleware() HandlerMiddleware

NewErrorSourceMiddleware returns a new backend.HandlerMiddleware that sets the error source in the context.Context, based on returned errors or query data response errors. If at least one query data response has a "downstream" error source and there isn't one with a "plugin" error source, the error source in the context is set to "downstream".

func NewLoggerMiddleware added in v0.255.0

func NewLoggerMiddleware(logger log.Logger, extractLogParamsFn func(ctx context.Context, pCtx PluginContext) []any) HandlerMiddleware

NewLoggerMiddleware creates a new HandlerMiddleware that will log requests.

func NewMetricsMiddleware added in v0.255.0

func NewMetricsMiddleware(registerer prometheus.Registerer, namespace string, includePluginID bool) HandlerMiddleware

NewMetricsMiddleware creates a new HandlerMiddleware that will record metrics for requests.

func NewTracingMiddleware added in v0.257.0

func NewTracingMiddleware(tracer trace.Tracer) HandlerMiddleware

NewTracingMiddleware creates a new HandlerMiddleware that will create traces/spans for requests.

type HandlerMiddlewareFunc added in v0.251.0

type HandlerMiddlewareFunc func(next Handler) Handler

The HandlerMiddlewareFunc type is an adapter to allow the use of ordinary functions as HandlerMiddleware's. If f is a function with the appropriate signature, HandlerMiddlewareFunc(f) is a HandlerMiddleware that calls f.

func (HandlerMiddlewareFunc) CreateHandlerMiddleware added in v0.251.0

func (fn HandlerMiddlewareFunc) CreateHandlerMiddleware(next Handler) Handler

CreateHandlerMiddleware implements the HandlerMiddleware interface.

type Handlers added in v0.257.0

Handlers implements Handler.

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 added in v0.67.0

func (hs HealthStatus) String() string

String textual representation of the status.

type InitialData added in v0.101.0

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

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

func NewInitialData added in v0.108.0

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

NewInitialData allows sending JSON on subscription

func NewInitialFrame added in v0.101.0

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

NewInitialFrame allows creating frame as subscription InitialData.

func (*InitialData) Data added in v0.101.0

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

Data allows to get prepared bytes of initial data.

type MiddlewareHandler added in v0.251.0

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

MiddlewareHandler decorates a Handler with HandlerMiddleware's.

func HandlerFromMiddlewares added in v0.251.0

func HandlerFromMiddlewares(finalHandler Handler, middlewares ...HandlerMiddleware) (*MiddlewareHandler, error)

HandlerFromMiddlewares creates a new MiddlewareHandler implementing Handler that decorates finalHandler with middlewares.

func (MiddlewareHandler) CallResource added in v0.251.0

func (MiddlewareHandler) CheckHealth added in v0.251.0

func (MiddlewareHandler) CollectMetrics added in v0.251.0

func (MiddlewareHandler) ConvertObjects added in v0.251.0

func (MiddlewareHandler) MutateAdmission added in v0.251.0

func (h MiddlewareHandler) MutateAdmission(ctx context.Context, req *AdmissionRequest) (*MutationResponse, error)

func (MiddlewareHandler) PublishStream added in v0.251.0

func (*MiddlewareHandler) QueryData added in v0.251.0

func (MiddlewareHandler) RunStream added in v0.251.0

func (h MiddlewareHandler) RunStream(ctx context.Context, req *RunStreamRequest, sender *StreamSender) error

func (MiddlewareHandler) SubscribeStream added in v0.251.0

func (MiddlewareHandler) ValidateAdmission added in v0.251.0

func (h MiddlewareHandler) ValidateAdmission(ctx context.Context, req *AdmissionRequest) (*ValidationResponse, error)

type MutateAdmissionFunc added in v0.232.0

type MutateAdmissionFunc func(context.Context, *AdmissionRequest) (*MutationResponse, error)

type MutationResponse added in v0.232.0

type MutationResponse struct {
	// Allowed indicates whether or not the admission request was permitted.
	Allowed bool `json:"allowed,omitempty"`
	// Result contains extra details into why an admission request was denied.
	// This field IS NOT consulted in any way if "Allowed" is "true".
	// +optional
	Result *StatusResult `json:"result,omitempty"`
	// warnings is a list of warning messages to return to the requesting API client.
	// Warning messages describe a problem the client making the API request should correct or be aware of.
	// Limit warnings to 120 characters if possible.
	// Warnings over 256 characters and large numbers of warnings may be truncated.
	// +optional
	Warnings []string `json:"warnings,omitempty"`
	// Mutated object bytes (when requested)
	// +optional
	ObjectBytes []byte `json:"object_bytes,omitempty"`
}

type PluginContext added in v0.54.0

type PluginContext struct {
	// OrgID is The Grafana 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 Grafana user making the request.
	//
	// Will not be provided if Grafana backend initiated the request,
	// for example when request is coming from Grafana Alerting.
	User *User

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

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

	// GrafanaConfig is the configuration settings provided by Grafana.
	GrafanaConfig *GrafanaCfg

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

	// The requested API version
	APIVersion string
}

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

func PluginConfigFromContext added in v0.237.0

func PluginConfigFromContext(ctx context.Context) PluginContext

PluginConfigFromContext returns PluginContext from context if available, otherwise empty PluginContext.

type Proxy added in v0.177.0

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

type PublishStreamHandler added in v0.251.0

type PublishStreamHandler interface {
	// 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(ctx context.Context, req *PublishStreamRequest) (*PublishStreamResponse, error)
}

PublishStreamHandler handles stream publication.

type PublishStreamHandlerFunc added in v0.251.0

type PublishStreamHandlerFunc func(ctx context.Context, req *PublishStreamRequest) (*PublishStreamResponse, error)

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

func (PublishStreamHandlerFunc) PublishStream added in v0.251.0

SubscribeStream calls fn(ctx, req, sender).

type PublishStreamRequest added in v0.91.0

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

PublishStreamRequest represents a request for a publish stream call.

type PublishStreamResponse added in v0.91.0

type PublishStreamResponse struct {
	Status PublishStreamStatus
	Data   json.RawMessage
}

PublishStreamResponse represents a response for a publish stream call.

type PublishStreamStatus added in v0.91.0

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 QueryConversionHandler added in v0.249.0

type QueryConversionHandler interface {
	// ConvertQuery is called to covert queries between different versions
	ConvertQueryDataRequest(ctx context.Context, req *QueryDataRequest) (*QueryConversionResponse, error)
}

type QueryConversionResponse added in v0.249.0

type QueryConversionResponse struct {
	// Converted queries. It should extend v0alpha1.Query
	Queries []any
	// Result contains extra details into why an conversion request was denied.
	// +optional
	Result *StatusResult
}

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 Grafana. 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 added in v0.61.0

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

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

func (QueryDataHandlerFunc) QueryData added in v0.61.0

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 added in v0.147.0

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 added in v0.147.0

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 added in v0.147.0

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

GetHTTPHeaders returns HTTP headers.

func (*QueryDataRequest) SetHTTPHeader added in v0.147.0

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 `json:"results"`
}

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

func NewQueryDataResponse added in v0.42.0

func NewQueryDataResponse() *QueryDataResponse

NewQueryDataResponse returns a QueryDataResponse with the Responses property initialized.

func (*QueryDataResponse) DeepCopy added in v0.213.0

func (r *QueryDataResponse) DeepCopy() *QueryDataResponse

func (*QueryDataResponse) DeepCopyInto added in v0.213.0

func (r *QueryDataResponse) DeepCopyInto(out *QueryDataResponse)

func (QueryDataResponse) MarshalJSON added in v0.90.0

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

MarshalJSON writes the results as json

func (*QueryDataResponse) UnmarshalJSON added in v0.90.0

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

UnmarshalJSON will read JSON into a QueryDataResponse

type RawObject added in v0.243.0

type RawObject struct {
	// Raw is the underlying serialization of this object.
	Raw []byte `json:"-" `
	// ContentType is the media type of the object.
	ContentType string `json:"-"`
}

type RequestStatus added in v0.240.0

type RequestStatus int
const (
	RequestStatusOK RequestStatus = iota
	RequestStatusCancelled
	RequestStatusError
)

func RequestStatusFromError added in v0.240.0

func RequestStatusFromError(err error) RequestStatus

func RequestStatusFromErrorString added in v0.240.0

func RequestStatusFromErrorString(errString string) RequestStatus

func RequestStatusFromProtoQueryDataResponse added in v0.240.0

func RequestStatusFromProtoQueryDataResponse(res *pluginv2.QueryDataResponse, err error) RequestStatus

func RequestStatusFromQueryDataResponse added in v0.240.0

func RequestStatusFromQueryDataResponse(res *QueryDataResponse, err error) RequestStatus

func (RequestStatus) String added in v0.240.0

func (status RequestStatus) String() string

type Responses added in v0.42.0

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 RunStreamHandler added in v0.251.0

type RunStreamHandler interface {
	// RunStream will be initiated by Grafana to consume a stream. RunStream will be
	// called once for the first client successfully subscribed to a channel path.
	// When Grafana 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(ctx context.Context, req *RunStreamRequest, sender *StreamSender) error
}

RunStreamHandler handles running of streams.

type RunStreamHandlerFunc added in v0.251.0

type RunStreamHandlerFunc func(ctx context.Context, req *RunStreamRequest, sender *StreamSender) error

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

func (RunStreamHandlerFunc) RunStream added in v0.251.0

func (fn RunStreamHandlerFunc) RunStream(ctx context.Context, req *RunStreamRequest, sender *StreamSender) error

RunStream calls fn(ctx, req, sender).

type RunStreamRequest added in v0.89.0

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

RunStreamRequest represents a request for a run stream call.

type SQLConfig added in v0.212.0

type SQLConfig struct {
	RowLimit                      int64
	DefaultMaxOpenConns           int
	DefaultMaxIdleConns           int
	DefaultMaxConnLifetimeSeconds int
}

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.
	StreamHandler StreamHandler

	// AdmissionHandler validates resource storage
	// This is EXPERIMENTAL and is a subject to change till Grafana 12
	AdmissionHandler AdmissionHandler

	// ConversionHandler converts resources between versions
	// This is EXPERIMENTAL and is a subject to change till Grafana 12
	ConversionHandler ConversionHandler

	// QueryConversionHandler converts queries between versions
	// This is EXPERIMENTAL and is a subject to change till Grafana 12
	QueryConversionHandler QueryConversionHandler

	// GRPCSettings settings for gPRC.
	GRPCSettings GRPCSettings

	// HandlerMiddlewares list of handler middlewares to decorate handlers with.
	HandlerMiddlewares []HandlerMiddleware
}

ServeOpts options for serving plugins.

func (ServeOpts) HandlerWithMiddlewares added in v0.257.0

func (opts ServeOpts) HandlerWithMiddlewares() (Handler, error)

type Status added in v0.142.0

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 added in v0.142.0

func (s Status) IsValid() bool

func (Status) String added in v0.142.0

func (s Status) String() string

type StatusResult added in v0.232.0

type StatusResult struct {
	// Status of the operation.
	// One of: "Success" or "Failure".
	// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
	// +optional
	Status string `json:"status,omitempty"`
	// A human-readable description of the status of this operation.
	// +optional
	Message string `json:"message,omitempty"`
	// A machine-readable description of why this operation is in the
	// "Failure" status. If this value is empty there
	// is no information available. A Reason clarifies an HTTP status
	// code but does not override it.
	// +optional
	Reason string `json:"reason,omitempty"`
	// Suggested HTTP return code for this status, 0 if not set.
	// +optional
	Code int32 `json:"code,omitempty"`
}

type StreamHandler added in v0.89.0

StreamHandler handles streams.

type StreamPacket added in v0.89.0

type StreamPacket struct {
	Data json.RawMessage
}

StreamPacket represents a stream packet.

type StreamPacketSender added in v0.89.0

type StreamPacketSender interface {
	Send(*StreamPacket) error
}

StreamPacketSender is used for sending StreamPacket responses.

type StreamSender added in v0.101.0

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

StreamSender allows sending data to a stream.

func NewStreamSender added in v0.101.0

func NewStreamSender(packetSender StreamPacketSender) *StreamSender

NewStreamSender createa a new StreamSender.

func (*StreamSender) SendBytes added in v0.113.0

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 added in v0.101.0

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

SendFrame allows sending data.Frame to a stream.

func (*StreamSender) SendJSON added in v0.101.0

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

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

type SubscribeStreamHandler added in v0.251.0

type SubscribeStreamHandler 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 Grafana Core. As soon as first subscriber joins channel RunStream
	// will be called.
	SubscribeStream(ctx context.Context, req *SubscribeStreamRequest) (*SubscribeStreamResponse, error)
}

SubscribeStreamHandler handles stream subscription.

type SubscribeStreamHandlerFunc added in v0.251.0

type SubscribeStreamHandlerFunc func(ctx context.Context, req *SubscribeStreamRequest) (*SubscribeStreamResponse, error)

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

func (SubscribeStreamHandlerFunc) SubscribeStream added in v0.251.0

SubscribeStream calls fn(ctx, req, sender).

type SubscribeStreamRequest added in v0.91.0

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

SubscribeStreamRequest represents a request for a subscribe stream call.

type SubscribeStreamResponse added in v0.91.0

type SubscribeStreamResponse struct {
	Status      SubscribeStreamStatus
	InitialData *InitialData
}

SubscribeStreamResponse represents a response for a subscribe stream call.

type SubscribeStreamStatus added in v0.91.0

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 added in v0.35.0

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 Grafana user.

func UserFromContext added in v0.237.0

func UserFromContext(ctx context.Context) *User

UserFromContext returns User from context if available, otherwise nil.

type ValidateAdmissionFunc added in v0.232.0

type ValidateAdmissionFunc func(context.Context, *AdmissionRequest) (*ValidationResponse, error)

type ValidationResponse added in v0.232.0

type ValidationResponse struct {
	// Allowed indicates whether or not the admission request was permitted.
	Allowed bool `json:"allowed,omitempty"`
	// Result contains extra details into why an admission request was denied.
	// This field IS NOT consulted in any way if "Allowed" is "true".
	// +optional
	Result *StatusResult `json:"result,omitempty"`
	// warnings is a list of warning messages to return to the requesting API client.
	// Warning messages describe a problem the client making the API request should correct or be aware of.
	// Limit warnings to 120 characters if possible.
	// Warnings over 256 characters and large numbers of warnings may be truncated.
	// +optional
	Warnings []string `json:"warnings,omitempty"`
}

Basic request to say if the validation was successful or not

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.
gtime provides utilities for parsing time, time ranges and time durations (intervals).
gtime provides utilities for parsing time, time ranges and time durations (intervals).
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.
internal
Package log provides a logging interface to send logs from plugins to Grafana server.
Package log provides a logging interface to send logs from plugins to Grafana 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