|
| 1 | +package plugin |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "math/rand" |
| 7 | + "time" |
| 8 | + |
| 9 | + "github.com/grafana/grafana-plugin-sdk-go/backend" |
| 10 | + "github.com/grafana/grafana-plugin-sdk-go/backend/instancemgmt" |
| 11 | + "github.com/grafana/grafana-plugin-sdk-go/backend/log" |
| 12 | + "github.com/grafana/grafana-plugin-sdk-go/data" |
| 13 | + "github.com/grafana/grafana-plugin-sdk-go/live" |
| 14 | +) |
| 15 | + |
| 16 | +// Make sure SampleDatasource implements required interfaces. This is important to do |
| 17 | +// since otherwise we will only get a not implemented error response from plugin in |
| 18 | +// runtime. In this example datasource instance implements backend.QueryDataHandler, |
| 19 | +// backend.CheckHealthHandler, backend.StreamHandler interfaces. Plugin should not |
| 20 | +// implement all these interfaces - only those which are required for a particular task. |
| 21 | +// For example if plugin does not need streaming functionality then you are free to remove |
| 22 | +// methods that implement backend.StreamHandler. Implementing instancemgmt.InstanceDisposer |
| 23 | +// is useful to clean up resources used by previous datasource instance when a new datasource |
| 24 | +// instance created upon datasource settings changed. |
| 25 | +var ( |
| 26 | + _ backend.QueryDataHandler = (*SampleDatasource)(nil) |
| 27 | + _ backend.CheckHealthHandler = (*SampleDatasource)(nil) |
| 28 | + _ backend.StreamHandler = (*SampleDatasource)(nil) |
| 29 | + _ instancemgmt.InstanceDisposer = (*SampleDatasource)(nil) |
| 30 | +) |
| 31 | + |
| 32 | +// NewSampleDatasource creates a new datasource instance. |
| 33 | +func NewSampleDatasource(_ backend.DataSourceInstanceSettings) (instancemgmt.Instance, error) { |
| 34 | + return &SampleDatasource{}, nil |
| 35 | +} |
| 36 | + |
| 37 | +// SampleDatasource is an example datasource which can respond to data queries, reports |
| 38 | +// its health and has streaming skills. |
| 39 | +type SampleDatasource struct{} |
| 40 | + |
| 41 | +// Dispose here tells plugin SDK that plugin wants to clean up resources when a new instance |
| 42 | +// created. As soon as datasource settings change detected by SDK old datasource instance will |
| 43 | +// be disposed and a new one will be created using NewSampleDatasource factory function. |
| 44 | +func (d *SampleDatasource) Dispose() { |
| 45 | + // Clean up datasource instance resources. |
| 46 | +} |
| 47 | + |
| 48 | +// QueryData handles multiple queries and returns multiple responses. |
| 49 | +// req contains the queries []DataQuery (where each query contains RefID as a unique identifier). |
| 50 | +// The QueryDataResponse contains a map of RefID to the response for each query, and each response |
| 51 | +// contains Frames ([]*Frame). |
| 52 | +func (d *SampleDatasource) QueryData(ctx context.Context, req *backend.QueryDataRequest) (*backend.QueryDataResponse, error) { |
| 53 | + log.DefaultLogger.Info("QueryData called", "request", req) |
| 54 | + |
| 55 | + // create response struct |
| 56 | + response := backend.NewQueryDataResponse() |
| 57 | + |
| 58 | + // loop over queries and execute them individually. |
| 59 | + for _, q := range req.Queries { |
| 60 | + res := d.query(ctx, req.PluginContext, q) |
| 61 | + |
| 62 | + // save the response in a hashmap |
| 63 | + // based on with RefID as identifier |
| 64 | + response.Responses[q.RefID] = res |
| 65 | + } |
| 66 | + |
| 67 | + return response, nil |
| 68 | +} |
| 69 | + |
| 70 | +type queryModel struct { |
| 71 | + WithStreaming bool `json:"withStreaming"` |
| 72 | +} |
| 73 | + |
| 74 | +func (d *SampleDatasource) query(_ context.Context, pCtx backend.PluginContext, query backend.DataQuery) backend.DataResponse { |
| 75 | + response := backend.DataResponse{} |
| 76 | + |
| 77 | + // Unmarshal the JSON into our queryModel. |
| 78 | + var qm queryModel |
| 79 | + |
| 80 | + response.Error = json.Unmarshal(query.JSON, &qm) |
| 81 | + if response.Error != nil { |
| 82 | + return response |
| 83 | + } |
| 84 | + |
| 85 | + // create data frame response. |
| 86 | + frame := data.NewFrame("response") |
| 87 | + |
| 88 | + // add fields. |
| 89 | + frame.Fields = append(frame.Fields, |
| 90 | + data.NewField("time", nil, []time.Time{query.TimeRange.From, query.TimeRange.To}), |
| 91 | + data.NewField("values", nil, []int64{10, 20}), |
| 92 | + ) |
| 93 | + |
| 94 | + // If query called with streaming on then return a channel |
| 95 | + // to subscribe on a client-side and consume updates from a plugin. |
| 96 | + // Feel free to remove this if you don't need streaming for your datasource. |
| 97 | + if qm.WithStreaming { |
| 98 | + channel := live.Channel{ |
| 99 | + Scope: live.ScopeDatasource, |
| 100 | + Namespace: pCtx.DataSourceInstanceSettings.UID, |
| 101 | + Path: "stream", |
| 102 | + } |
| 103 | + frame.SetMeta(&data.FrameMeta{Channel: channel.String()}) |
| 104 | + } |
| 105 | + |
| 106 | + // add the frames to the response. |
| 107 | + response.Frames = append(response.Frames, frame) |
| 108 | + |
| 109 | + return response |
| 110 | +} |
| 111 | + |
| 112 | +// CheckHealth handles health checks sent from Grafana to the plugin. |
| 113 | +// The main use case for these health checks is the test button on the |
| 114 | +// datasource configuration page which allows users to verify that |
| 115 | +// a datasource is working as expected. |
| 116 | +func (d *SampleDatasource) CheckHealth(_ context.Context, req *backend.CheckHealthRequest) (*backend.CheckHealthResult, error) { |
| 117 | + log.DefaultLogger.Info("CheckHealth called", "request", req) |
| 118 | + |
| 119 | + var status = backend.HealthStatusOk |
| 120 | + var message = "Data source is working" |
| 121 | + |
| 122 | + if rand.Int()%2 == 0 { |
| 123 | + status = backend.HealthStatusError |
| 124 | + message = "randomized error" |
| 125 | + } |
| 126 | + |
| 127 | + return &backend.CheckHealthResult{ |
| 128 | + Status: status, |
| 129 | + Message: message, |
| 130 | + }, nil |
| 131 | +} |
| 132 | + |
| 133 | +// SubscribeStream is called when a client wants to connect to a stream. This callback |
| 134 | +// allows sending the first message. |
| 135 | +func (d *SampleDatasource) SubscribeStream(_ context.Context, req *backend.SubscribeStreamRequest) (*backend.SubscribeStreamResponse, error) { |
| 136 | + log.DefaultLogger.Info("SubscribeStream called", "request", req) |
| 137 | + |
| 138 | + status := backend.SubscribeStreamStatusPermissionDenied |
| 139 | + if req.Path == "stream" { |
| 140 | + // Allow subscribing only on expected path. |
| 141 | + status = backend.SubscribeStreamStatusOK |
| 142 | + } |
| 143 | + return &backend.SubscribeStreamResponse{ |
| 144 | + Status: status, |
| 145 | + }, nil |
| 146 | +} |
| 147 | + |
| 148 | +// RunStream is called once for any open channel. Results are shared with everyone |
| 149 | +// subscribed to the same channel. |
| 150 | +func (d *SampleDatasource) RunStream(ctx context.Context, req *backend.RunStreamRequest, sender *backend.StreamSender) error { |
| 151 | + log.DefaultLogger.Info("RunStream called", "request", req) |
| 152 | + |
| 153 | + // Create the same data frame as for query data. |
| 154 | + frame := data.NewFrame("response") |
| 155 | + |
| 156 | + // Add fields (matching the same schema used in QueryData). |
| 157 | + frame.Fields = append(frame.Fields, |
| 158 | + data.NewField("time", nil, make([]time.Time, 1)), |
| 159 | + data.NewField("values", nil, make([]int64, 1)), |
| 160 | + ) |
| 161 | + |
| 162 | + counter := 0 |
| 163 | + |
| 164 | + // Stream data frames periodically till stream closed by Grafana. |
| 165 | + for { |
| 166 | + select { |
| 167 | + case <-ctx.Done(): |
| 168 | + log.DefaultLogger.Info("Context done, finish streaming", "path", req.Path) |
| 169 | + return nil |
| 170 | + case <-time.After(time.Second): |
| 171 | + // Send new data periodically. |
| 172 | + frame.Fields[0].Set(0, time.Now()) |
| 173 | + frame.Fields[1].Set(0, int64(10*(counter%2+1))) |
| 174 | + |
| 175 | + counter++ |
| 176 | + |
| 177 | + err := sender.SendFrame(frame, data.IncludeAll) |
| 178 | + if err != nil { |
| 179 | + log.DefaultLogger.Error("Error sending frame", "error", err) |
| 180 | + continue |
| 181 | + } |
| 182 | + } |
| 183 | + } |
| 184 | +} |
| 185 | + |
| 186 | +// PublishStream is called when a client sends a message to the stream. |
| 187 | +func (d *SampleDatasource) PublishStream(_ context.Context, req *backend.PublishStreamRequest) (*backend.PublishStreamResponse, error) { |
| 188 | + log.DefaultLogger.Info("PublishStream called", "request", req) |
| 189 | + |
| 190 | + // Do not allow publishing at all. |
| 191 | + return &backend.PublishStreamResponse{ |
| 192 | + Status: backend.PublishStreamStatusPermissionDenied, |
| 193 | + }, nil |
| 194 | +} |
0 commit comments