Skip to content

Commit

Permalink
Fix backend linter errors
Browse files Browse the repository at this point in the history
  • Loading branch information
alexanderzobnin committed Aug 30, 2023
1 parent a536e6d commit c06683c
Show file tree
Hide file tree
Showing 12 changed files with 81 additions and 72 deletions.
26 changes: 25 additions & 1 deletion pkg/datasource/functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,10 @@ func applyFunctionsPre(query *QueryModel, items []*zabbix.Item) error {

func applyGroupBy(series timeseries.TimeSeries, params ...interface{}) (timeseries.TimeSeries, error) {
pInterval, err := MustString(params[0])
if err != nil {
return nil, errParsingFunctionParam(err)
}

pAgg, err := MustString(params[1])
if err != nil {
return nil, errParsingFunctionParam(err)
Expand All @@ -169,6 +173,10 @@ func applyGroupBy(series timeseries.TimeSeries, params ...interface{}) (timeseri

func applyPercentile(series timeseries.TimeSeries, params ...interface{}) (timeseries.TimeSeries, error) {
pInterval, err := MustString(params[0])
if err != nil {
return nil, errParsingFunctionParam(err)
}

percentile, err := MustFloat64(params[1])
if err != nil {
return nil, errParsingFunctionParam(err)
Expand Down Expand Up @@ -275,6 +283,10 @@ func applyExponentialMovingAverage(series timeseries.TimeSeries, params ...inter

func applyAggregateBy(series []*timeseries.TimeSeriesData, params ...interface{}) ([]*timeseries.TimeSeriesData, error) {
pInterval, err := MustString(params[0])
if err != nil {
return nil, errParsingFunctionParam(err)
}

pAgg, err := MustString(params[1])
if err != nil {
return nil, errParsingFunctionParam(err)
Expand Down Expand Up @@ -303,6 +315,10 @@ func applySumSeries(series []*timeseries.TimeSeriesData, params ...interface{})

func applyPercentileAgg(series []*timeseries.TimeSeriesData, params ...interface{}) ([]*timeseries.TimeSeriesData, error) {
pInterval, err := MustString(params[0])
if err != nil {
return nil, errParsingFunctionParam(err)
}

percentile, err := MustFloat64(params[1])
if err != nil {
return nil, errParsingFunctionParam(err)
Expand Down Expand Up @@ -331,6 +347,10 @@ func applyPercentileAgg(series []*timeseries.TimeSeriesData, params ...interface

func applyTop(series []*timeseries.TimeSeriesData, params ...interface{}) ([]*timeseries.TimeSeriesData, error) {
n, err := MustFloat64(params[0])
if err != nil {
return nil, errParsingFunctionParam(err)
}

pAgg, err := MustString(params[1])
if err != nil {
return nil, errParsingFunctionParam(err)
Expand All @@ -343,6 +363,10 @@ func applyTop(series []*timeseries.TimeSeriesData, params ...interface{}) ([]*ti

func applyBottom(series []*timeseries.TimeSeriesData, params ...interface{}) ([]*timeseries.TimeSeriesData, error) {
n, err := MustFloat64(params[0])
if err != nil {
return nil, errParsingFunctionParam(err)
}

pAgg, err := MustString(params[1])
if err != nil {
return nil, errParsingFunctionParam(err)
Expand Down Expand Up @@ -413,7 +437,7 @@ func applyTimeShiftPost(series timeseries.TimeSeries, params ...interface{}) (ti
if interval == 0 {
return series, nil
}
if shiftForward == true {
if shiftForward {
interval = -interval
}

Expand Down
35 changes: 28 additions & 7 deletions pkg/datasource/resource_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ package datasource

import (
"encoding/json"
"io/ioutil"
"io"
"net/http"
"time"

"github.com/alexanderzobnin/grafana-zabbix/pkg/zabbix"

"github.com/grafana/grafana-plugin-sdk-go/backend/log"
"github.com/grafana/grafana-plugin-sdk-go/backend/resource/httpadapter"
)

Expand All @@ -17,7 +19,11 @@ import (
func (ds *ZabbixDatasource) RootHandler(rw http.ResponseWriter, req *http.Request) {
ds.logger.Debug("Received resource call", "url", req.URL.String(), "method", req.Method)

rw.Write([]byte("Hello from Zabbix data source!"))
_, err := rw.Write([]byte("Hello from Zabbix data source!"))
if err != nil {
ds.logger.Warn("Error writing response")
}

rw.WriteHeader(http.StatusOK)
}

Expand All @@ -26,7 +32,7 @@ func (ds *ZabbixDatasource) ZabbixAPIHandler(rw http.ResponseWriter, req *http.R
return
}

body, err := ioutil.ReadAll(req.Body)
body, err := io.ReadAll(req.Body)
defer req.Body.Close()
if err != nil || len(body) == 0 {
writeError(rw, http.StatusBadRequest, err)
Expand Down Expand Up @@ -67,7 +73,7 @@ func (ds *ZabbixDatasource) DBConnectionPostProcessingHandler(rw http.ResponseWr
return
}

body, err := ioutil.ReadAll(req.Body)
body, err := io.ReadAll(req.Body)
defer req.Body.Close()
if err != nil || len(body) == 0 {
writeError(rw, http.StatusBadRequest, err)
Expand Down Expand Up @@ -95,6 +101,9 @@ func (ds *ZabbixDatasource) DBConnectionPostProcessingHandler(rw http.ResponseWr
reqData.Query.TimeRange.To = time.Unix(reqData.TimeRange.To, 0)

frames, err := dsInstance.applyDataProcessing(req.Context(), &reqData.Query, reqData.Series, true)
if err != nil {
writeError(rw, http.StatusInternalServerError, err)
}

resultJson, err := json.Marshal(frames)
if err != nil {
Expand All @@ -103,7 +112,11 @@ func (ds *ZabbixDatasource) DBConnectionPostProcessingHandler(rw http.ResponseWr

rw.Header().Add("Content-Type", "application/json")
rw.WriteHeader(http.StatusOK)
rw.Write(resultJson)

_, err = rw.Write(resultJson)
if err != nil {
ds.logger.Warn("Error writing response")
}

}

Expand All @@ -115,7 +128,11 @@ func writeResponse(rw http.ResponseWriter, result *ZabbixAPIResourceResponse) {

rw.Header().Add("Content-Type", "application/json")
rw.WriteHeader(http.StatusOK)
rw.Write(resultJson)

_, err = rw.Write(resultJson)
if err != nil {
log.DefaultLogger.Warn("Error writing response")
}
}

func writeError(rw http.ResponseWriter, statusCode int, err error) {
Expand All @@ -132,5 +149,9 @@ func writeError(rw http.ResponseWriter, statusCode int, err error) {

rw.Header().Add("Content-Type", "application/json")
rw.WriteHeader(http.StatusInternalServerError)
rw.Write(b)

_, err = rw.Write(b)
if err != nil {
log.DefaultLogger.Warn("Error writing response")
}
}
4 changes: 4 additions & 0 deletions pkg/datasource/zabbix.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@ func (ds *ZabbixDatasourceInstance) queryNumericItems(ctx context.Context, query
var items []*zabbix.Item
var err error
zabbixVersion, err := ds.zabbix.GetVersion(ctx)
if err != nil {
ds.logger.Warn("Error getting Zabbix version")
}

if zabbixVersion >= 54 {
items, err = ds.zabbix.GetItems(ctx, groupFilter, hostFilter, itemTagFilter, itemFilter, "num", showDisabled)
} else {
Expand Down
9 changes: 0 additions & 9 deletions pkg/datasource/zabbix_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,13 @@ import (
"github.com/grafana/grafana-plugin-sdk-go/backend/log"
)

var emptyParams = map[string]interface{}{}

var basicDatasourceInfo = &backend.DataSourceInstanceSettings{
ID: 1,
Name: "TestDatasource",
URL: "http://zabbix.org/zabbix",
JSONData: []byte(`{"username":"username", "password":"password", "cacheTTL":"10m", "authType":"token"}`),
}

func mockZabbixQuery(method string, params zabbix.ZabbixAPIParams) *zabbix.ZabbixAPIRequest {
return &zabbix.ZabbixAPIRequest{
Method: method,
Params: params,
}
}

func MockZabbixDataSource(body string, statusCode int) *ZabbixDatasourceInstance {
zabbixSettings, _ := settings.ReadZabbixSettings(basicDatasourceInfo)
zabbixClient, _ := zabbix.MockZabbixClient(basicDatasourceInfo, body, statusCode)
Expand Down
5 changes: 5 additions & 0 deletions pkg/httpclient/httpclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"time"

simplejson "github.com/bitly/go-simplejson"

"github.com/grafana/grafana-plugin-sdk-go/backend"
"github.com/grafana/grafana-plugin-sdk-go/backend/httpclient"
"github.com/grafana/grafana-plugin-sdk-go/backend/log"
Expand All @@ -14,6 +15,10 @@ import (
// New creates new HTTP client.
func New(dsInfo *backend.DataSourceInstanceSettings, timeout time.Duration) (*http.Client, error) {
clientOptions, err := dsInfo.HTTPClientOptions()
if err != nil {
return nil, err
}

clientOptions.Timeouts.Timeout = timeout

tlsSkipVerify, err := getTLSSkipVerify(dsInfo)
Expand Down
2 changes: 1 addition & 1 deletion pkg/timeseries/agg_functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ func AggPercentile(n float64) AggregationFunc {
return nil
}

sort.Sort(sort.Float64Slice(values))
sort.Float64s(values)
percentileIndex := int(math.Floor(float64(len(values)) * n / 100))
percentile := values[percentileIndex]
return &percentile
Expand Down
3 changes: 1 addition & 2 deletions pkg/timeseries/align.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,12 +129,11 @@ func PrepareForStack(series []*TimeSeriesData) []*TimeSeriesData {
p := s.TS[0]
pNext := s.TS[1]
interpolatedSeries := make([]TimePoint, 0)
interpolatedTS := interpolatedTimeStamps[0]
interpolatedTSIdx := 0

// Insert nulls before the first point
for i := 0; i < len(interpolatedTimeStamps); i++ {
interpolatedTS = interpolatedTimeStamps[i]
interpolatedTS := interpolatedTimeStamps[i]
if interpolatedTS.Before(p.Time) {
interpolatedSeries = append(interpolatedSeries, TimePoint{Time: interpolatedTS, Value: nil})
} else {
Expand Down
35 changes: 0 additions & 35 deletions pkg/timeseries/timeseries.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ import (
"math"
"sort"
"time"

"github.com/grafana/grafana-plugin-sdk-go/data"
)

func NewTimeSeriesData() *TimeSeriesData {
Expand Down Expand Up @@ -309,36 +307,3 @@ func findNearestLeft(series TimeSeries, pointIndex int) *TimePoint {
}
return nil
}

func getTimeFieldIndex(frame *data.Frame) int {
for i := 0; i < len(frame.Fields); i++ {
if frame.Fields[i].Type() == data.FieldTypeTime {
return i
}
}

return -1
}

func getTimestampAt(frame *data.Frame, index int) *time.Time {
timeFieldIdx := getTimeFieldIndex(frame)
if timeFieldIdx < 0 {
return nil
}

tsValue := frame.Fields[timeFieldIdx].At(index)
ts, ok := tsValue.(time.Time)
if !ok {
return nil
}

return &ts
}

func setTimeAt(frame *data.Frame, frameTs time.Time, index int) {
for _, field := range frame.Fields {
if field.Type() == data.FieldTypeTime {
field.Insert(index, frameTs)
}
}
}
21 changes: 11 additions & 10 deletions pkg/zabbix/methods.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,9 @@ func (ds *Zabbix) GetItems(
itemTagFilter = strings.Join(tagStrs, ",")
}
allItems, err = ds.GetAllItems(ctx, hostids, nil, itemType, showDisabled, itemTagFilter)
if err != nil {
return nil, err
}

return filterItemsByQuery(allItems, itemFilter)
}
Expand Down Expand Up @@ -153,6 +156,9 @@ func (ds *Zabbix) GetItemsBefore54(
} else if appFilter == "" && len(hostids) > 0 {
allItems, err = ds.GetAllItems(ctx, hostids, nil, itemType, showDisabled, "")
}
if err != nil {
return nil, err
}

return filterItemsByQuery(allItems, itemFilter)
}
Expand Down Expand Up @@ -239,7 +245,11 @@ func (ds *Zabbix) GetItemTags(ctx context.Context, groupFilter string, hostFilte
var allItems []*Item
itemType := "num"
showDisabled := false

allItems, err = ds.GetAllItems(ctx, hostids, nil, itemType, showDisabled, "")
if err != nil {
return nil, err
}

var allTags []ItemTag
tagsMap := make(map[string]ItemTag)
Expand Down Expand Up @@ -397,7 +407,7 @@ func (ds *Zabbix) GetAllItems(ctx context.Context, hostids []string, appids []st
}
}

if showDisabled == false {
if !showDisabled {
params["monitored"] = true
}

Expand Down Expand Up @@ -521,12 +531,3 @@ func (ds *Zabbix) GetVersion(ctx context.Context) (int, error) {
versionNum, err := strconv.Atoi(version)
return versionNum, err
}

func isAppMethodNotFoundError(err error) bool {
if err == nil {
return false
}

message := err.Error()
return message == `Method not found. Incorrect API "application".`
}
5 changes: 2 additions & 3 deletions pkg/zabbix/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ func (item *Item) ExpandItemName() string {
name := item.Name
key := item.Key

if strings.Index(key, "[") == -1 {
if !strings.Contains(key, "[") {
return name
}

Expand All @@ -34,14 +34,13 @@ func expandItems(items []*Item) []*Item {
}

func splitKeyParams(paramStr string) []string {
paramRunes := []rune(paramStr)
params := []string{}
quoted := false
inArray := false
splitSymbol := ","
param := ""

for _, r := range paramRunes {
for _, r := range paramStr {
symbol := string(r)
if symbol == `"` && inArray {
param += symbol
Expand Down
4 changes: 2 additions & 2 deletions pkg/zabbixapi/testing.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package zabbixapi

import (
"bytes"
"io/ioutil"
"io"
"net/http"
"net/url"

Expand Down Expand Up @@ -36,7 +36,7 @@ func MockZabbixAPI(body string, statusCode int) (*ZabbixAPI, error) {
httpClient: NewTestClient(func(req *http.Request) *http.Response {
return &http.Response{
StatusCode: statusCode,
Body: ioutil.NopCloser(bytes.NewBufferString(body)),
Body: io.NopCloser(bytes.NewBufferString(body)),
Header: make(http.Header),
}
}),
Expand Down
Loading

0 comments on commit c06683c

Please sign in to comment.