Initial Commit

This commit is contained in:
Alec Sears
2019-10-15 17:18:42 -05:00
parent e8c5c0c3b9
commit 7c3f26a7f4
8 changed files with 266 additions and 45 deletions

6
go.mod
View File

@@ -5,10 +5,14 @@ go 1.12
require ( require (
github.com/bitly/go-simplejson v0.5.0 github.com/bitly/go-simplejson v0.5.0
github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 // indirect github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 // indirect
github.com/google/go-cmp v0.3.1 // indirect
github.com/grafana/grafana_plugin_model v0.0.0-20180518082423-84176c64269d github.com/grafana/grafana_plugin_model v0.0.0-20180518082423-84176c64269d
github.com/hashicorp/go-hclog v0.9.2 github.com/hashicorp/go-hclog v0.9.2
github.com/hashicorp/go-plugin v1.0.1 github.com/hashicorp/go-plugin v1.0.1
github.com/kr/pretty v0.1.0 // indirect github.com/kr/pretty v0.1.0 // indirect
github.com/patrickmn/go-cache v2.1.0+incompatible github.com/patrickmn/go-cache v2.1.0+incompatible
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d github.com/pkg/errors v0.8.1 // indirect
golang.org/x/net v0.0.0-20190620200207-3b0461eec859
golang.org/x/sync v0.0.0-20190423024810-112230192c58 // indirect
gotest.tools v2.2.0+incompatible
) )

15
go.sum
View File

@@ -5,9 +5,12 @@ github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869/go.mod h1:Ekp36dR
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/google/go-cmp v0.3.1 h1:Xye71clBPdm5HgqGwUkwhbynsUJZhDbS20FvLhQ2izg=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/grafana/grafana_plugin_model v0.0.0-20180518082423-84176c64269d h1:Ep6bjWDwurT9NpUATiqa8NYIllmZbLDXLn6Ib4lCtAA= github.com/grafana/grafana_plugin_model v0.0.0-20180518082423-84176c64269d h1:Ep6bjWDwurT9NpUATiqa8NYIllmZbLDXLn6Ib4lCtAA=
github.com/grafana/grafana_plugin_model v0.0.0-20180518082423-84176c64269d/go.mod h1:70BFhO60E3e7kq+ssiouwX/HX5DvQ3L6XffdH0S2YfU= github.com/grafana/grafana_plugin_model v0.0.0-20180518082423-84176c64269d/go.mod h1:70BFhO60E3e7kq+ssiouwX/HX5DvQ3L6XffdH0S2YfU=
github.com/hashicorp/go-hclog v0.0.0-20180709165350-ff2cf002a8dd/go.mod h1:9bjs9uLqI8l75knNv3lV1kA55veR+WUPSiKIWcQHudI= github.com/hashicorp/go-hclog v0.0.0-20180709165350-ff2cf002a8dd/go.mod h1:9bjs9uLqI8l75knNv3lV1kA55veR+WUPSiKIWcQHudI=
@@ -28,20 +31,32 @@ github.com/oklog/run v1.0.0 h1:Ru7dDtJNOyC66gQ5dQmaCa0qIsAUFY3sFpK1Xk8igrw=
github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA= github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA=
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc= github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ= github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d h1:g9qWBGx4puODJTMVyoPrpoxPFgVGd+z1DZwjfRu4d0I= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d h1:g9qWBGx4puODJTMVyoPrpoxPFgVGd+z1DZwjfRu4d0I=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859 h1:R/3boaszxrf1GEUWTVDzSKVwLmSJpwZ1yqXm8j0v2QI=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4 h1:YUO/7uOKsKeq9UokNS62b8FYywz3ker1l1vDZRCRefw=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58 h1:8gQV6CLnAEikrhgkHFbMAEhagSSnXWGV915qUMm9mrU=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190129075346-302c3dd5f1cc h1:WiYx1rIFmx8c0mXAFtv5D/mHyKe1+jmuP7PViuwqwuQ= golang.org/x/sys v0.0.0-20190129075346-302c3dd5f1cc h1:WiYx1rIFmx8c0mXAFtv5D/mHyKe1+jmuP7PViuwqwuQ=
golang.org/x/sys v0.0.0-20190129075346-302c3dd5f1cc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190129075346-302c3dd5f1cc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a h1:1BGLXjeY4akVXGgbC9HugT3Jv3hCI0z56oJR5vAMgBU=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8 h1:Nw54tB0rB7hY/N0NQvRW8DG4Yk3Q6T9cu9RcFQDu1tc= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8 h1:Nw54tB0rB7hY/N0NQvRW8DG4Yk3Q6T9cu9RcFQDu1tc=
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/grpc v1.14.0 h1:ArxJuB1NWfPY6r9Gp9gqwplT0Ge7nqv9msgu03lHLmo= google.golang.org/grpc v1.14.0 h1:ArxJuB1NWfPY6r9Gp9gqwplT0Ge7nqv9msgu03lHLmo=
google.golang.org/grpc v1.14.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.14.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw=
gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo=
gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw=

View File

@@ -3,8 +3,10 @@ package main
import ( import (
"crypto/sha1" "crypto/sha1"
"encoding/hex" "encoding/hex"
"encoding/json"
"time" "time"
"github.com/grafana/grafana_plugin_model/go/datasource"
cache "github.com/patrickmn/go-cache" cache "github.com/patrickmn/go-cache"
) )
@@ -30,9 +32,18 @@ func (c *Cache) Get(request string) (interface{}, bool) {
return c.cache.Get(request) return c.cache.Get(request)
} }
// Hash converts the given text string to hash string // HashString converts the given text string to hash string
func Hash(text string) string { func HashString(text string) string {
hash := sha1.New() hash := sha1.New()
hash.Write([]byte(text)) hash.Write([]byte(text))
return hex.EncodeToString(hash.Sum(nil)) return hex.EncodeToString(hash.Sum(nil))
} }
// HashDatasourceInfo converts the given datasource info to hash string
func HashDatasourceInfo(dsInfo *datasource.DatasourceInfo) string {
digester := sha1.New()
if err := json.NewEncoder(digester).Encode(dsInfo); err != nil {
panic(err) // This shouldn't be possible but just in case DatasourceInfo changes
}
return hex.EncodeToString(digester.Sum(nil))
}

68
pkg/cache_test.go Normal file
View File

@@ -0,0 +1,68 @@
package main
import (
"testing"
"github.com/grafana/grafana_plugin_model/go/datasource"
"gotest.tools/assert"
)
func TestHashDatasourceInfo(t *testing.T) {
tests := []struct {
name string
dsInfo *datasource.DatasourceInfo
want string
}{
{
name: "Normal Datasource Info",
dsInfo: &datasource.DatasourceInfo{
Id: 1,
OrgId: 1,
Name: "Zabbix",
Type: "alexanderzobnin-zabbix-datasource",
Url: "https://localhost:3306/zabbix/api_jsonrpc.php",
JsonData: "{}",
DecryptedSecureJsonData: map[string]string{
"username": "grafanaZabbixUser",
"password": "$uper$ecr3t!!!",
},
},
want: "ed161f89179c46d9a578e4d7e92ff95444222e0a",
},
// Can't find a case where the input causes the encoder to fail
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := HashDatasourceInfo(tt.dsInfo)
assert.Equal(t, tt.want, got)
})
}
}
func BenchmarkHashDatasourceInfo(b *testing.B) {
benches := []struct {
name string
dsInfo *datasource.DatasourceInfo
}{
{
"Normal Datasource Info",
&datasource.DatasourceInfo{
Id: 4,
OrgId: 6,
Name: "MyZabbixDatasource",
Type: "alexanderzobnin-zabbix-datasource",
Url: "https://localhost:3306/zabbix/api_jsonrpc.php",
JsonData: `{ "addThresholds": true, "disableReadOnlyUsersAck": true }`,
DecryptedSecureJsonData: map[string]string{
"username": "grafanaZabbixUser",
"password": "$uper$ecr3t!!!",
},
},
},
}
for _, bt := range benches {
b.Run(bt.name, func(b *testing.B) {
HashDatasourceInfo(bt.dsInfo)
})
}
}

View File

@@ -2,6 +2,7 @@ package main
import ( import (
"errors" "errors"
"fmt"
simplejson "github.com/bitly/go-simplejson" simplejson "github.com/bitly/go-simplejson"
"github.com/grafana/grafana_plugin_model/go/datasource" "github.com/grafana/grafana_plugin_model/go/datasource"
@@ -10,39 +11,63 @@ import (
"golang.org/x/net/context" "golang.org/x/net/context"
) )
type ZabbixDatasource struct { // ZabbixBackend implements the Grafana backend interface and forwards queries to the ZabbixDatasource
type ZabbixBackend struct {
plugin.NetRPCUnsupportedPlugin plugin.NetRPCUnsupportedPlugin
logger hclog.Logger logger hclog.Logger
datasourceCache *Cache
} }
func (ds *ZabbixDatasource) Query(ctx context.Context, tsdbReq *datasource.DatasourceRequest) (*datasource.DatasourceResponse, error) { func (b *ZabbixBackend) newZabbixDatasource() *ZabbixDatasource {
ds := NewZabbixDatasource()
ds.logger = b.logger
return ds
}
// Query receives requests from the Grafana backend. Requests are filtered by query type and sent to the
// applicable ZabbixDatasource.
func (b *ZabbixBackend) Query(ctx context.Context, tsdbReq *datasource.DatasourceRequest) (*datasource.DatasourceResponse, error) {
zabbixDs := b.getCachedDatasource(tsdbReq)
queryType, err := GetQueryType(tsdbReq) queryType, err := GetQueryType(tsdbReq)
if err != nil { if err != nil {
return nil, err return nil, err
} }
dsInfo := tsdbReq.GetDatasource()
ds.logger.Debug("createRequest", "dsInfo", dsInfo)
ds.logger.Debug("createRequest", "queryType", queryType)
switch queryType { switch queryType {
case "zabbixAPI": case "zabbixAPI":
return ds.ZabbixAPIQuery(ctx, tsdbReq) return zabbixDs.ZabbixAPIQuery(ctx, tsdbReq)
default: default:
return nil, errors.New("Query is not implemented yet") return nil, errors.New("Query is not implemented yet")
} }
} }
func (b *ZabbixBackend) getCachedDatasource(tsdbReq *datasource.DatasourceRequest) *ZabbixDatasource {
dsInfoHash := HashDatasourceInfo(tsdbReq.GetDatasource())
if cachedData, ok := b.datasourceCache.Get(dsInfoHash); ok {
if cachedDS, ok := cachedData.(*ZabbixDatasource); ok {
return cachedDS
}
}
if b.logger.IsDebug() {
dsInfo := tsdbReq.GetDatasource()
b.logger.Debug(fmt.Sprintf("Datasource cache miss (Org %d Id %d '%s' %s)", dsInfo.GetOrgId(), dsInfo.GetId(), dsInfo.GetName(), dsInfoHash))
}
return b.newZabbixDatasource()
}
// GetQueryType determines the query type from a query or list of queries
func GetQueryType(tsdbReq *datasource.DatasourceRequest) (string, error) { func GetQueryType(tsdbReq *datasource.DatasourceRequest) (string, error) {
queryType := "query" queryType := "query"
if len(tsdbReq.Queries) > 0 { if len(tsdbReq.Queries) > 0 {
firstQuery := tsdbReq.Queries[0] firstQuery := tsdbReq.Queries[0]
queryJson, err := simplejson.NewJson([]byte(firstQuery.ModelJson)) queryJSON, err := simplejson.NewJson([]byte(firstQuery.ModelJson))
if err != nil { if err != nil {
return "", err return "", err
} }
queryType = queryJson.Get("queryType").MustString("query") queryType = queryJSON.Get("queryType").MustString("query")
} }
return queryType, nil return queryType, nil
} }

81
pkg/datasource_test.go Normal file
View File

@@ -0,0 +1,81 @@
package main
import (
"testing"
"github.com/grafana/grafana_plugin_model/go/datasource"
hclog "github.com/hashicorp/go-hclog"
cache "github.com/patrickmn/go-cache"
"gotest.tools/assert"
)
func TestZabbixBackend_getCachedDatasource(t *testing.T) {
basicDatasourceInfo := &datasource.DatasourceInfo{
Id: 1,
Name: "TestDatasource",
}
basicDatasourceInfoHash := HashDatasourceInfo(basicDatasourceInfo)
modifiedDatasource := NewZabbixDatasource()
modifiedDatasource.authToken = "AB404F1234"
altDatasourceInfo := &datasource.DatasourceInfo{
Id: 2,
Name: "AnotherDatasource",
}
altDatasourceInfoHash := HashDatasourceInfo(altDatasourceInfo)
tests := []struct {
name string
cache *cache.Cache
request *datasource.DatasourceRequest
want *ZabbixDatasource
}{
{
name: "Uncached Datasource (nothing in cache)",
request: &datasource.DatasourceRequest{
Datasource: basicDatasourceInfo,
},
want: NewZabbixDatasource(),
},
{
name: "Uncached Datasource (cache miss)",
cache: cache.NewFrom(cache.NoExpiration, cache.NoExpiration, map[string]cache.Item{
basicDatasourceInfoHash: cache.Item{Object: modifiedDatasource},
}),
request: &datasource.DatasourceRequest{
Datasource: altDatasourceInfo,
},
want: NewZabbixDatasource(),
},
{
name: "Cached Datasource",
cache: cache.NewFrom(cache.NoExpiration, cache.NoExpiration, map[string]cache.Item{
altDatasourceInfoHash: cache.Item{Object: NewZabbixDatasource()},
basicDatasourceInfoHash: cache.Item{Object: modifiedDatasource},
}),
request: &datasource.DatasourceRequest{
Datasource: basicDatasourceInfo,
},
want: modifiedDatasource,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.cache == nil {
tt.cache = cache.New(cache.NoExpiration, cache.NoExpiration)
}
b := &ZabbixBackend{
logger: hclog.New(&hclog.LoggerOptions{
Name: "TestZabbixBackend_getCachedDatasource",
Level: hclog.LevelFromString("DEBUG"),
}),
datasourceCache: &Cache{cache: tt.cache},
}
got := b.getCachedDatasource(tt.request)
// Only checking the authToken, being the easiest value to, and guarantee equality for
assert.Equal(t, tt.want.authToken, got.authToken)
})
}
}

View File

@@ -1,6 +1,8 @@
package main package main
import ( import (
"time"
"github.com/grafana/grafana_plugin_model/go/datasource" "github.com/grafana/grafana_plugin_model/go/datasource"
hclog "github.com/hashicorp/go-hclog" hclog "github.com/hashicorp/go-hclog"
plugin "github.com/hashicorp/go-plugin" plugin "github.com/hashicorp/go-plugin"
@@ -22,7 +24,8 @@ func main() {
MagicCookieValue: "datasource", MagicCookieValue: "datasource",
}, },
Plugins: map[string]plugin.Plugin{ Plugins: map[string]plugin.Plugin{
"zabbix-backend-datasource": &datasource.DatasourcePluginImpl{Plugin: &ZabbixDatasource{ "zabbix-backend-datasource": &datasource.DatasourcePluginImpl{Plugin: &ZabbixBackend{
datasourceCache: NewCache(10*time.Minute, 10*time.Minute),
logger: pluginLogger, logger: pluginLogger,
}}, }},
}, },

View File

@@ -15,11 +15,25 @@ import (
simplejson "github.com/bitly/go-simplejson" simplejson "github.com/bitly/go-simplejson"
"github.com/grafana/grafana_plugin_model/go/datasource" "github.com/grafana/grafana_plugin_model/go/datasource"
hclog "github.com/hashicorp/go-hclog"
"golang.org/x/net/context" "golang.org/x/net/context"
"golang.org/x/net/context/ctxhttp" "golang.org/x/net/context/ctxhttp"
) )
var httpClient = &http.Client{ // ZabbixDatasource stores state about a specific datasource and provides methods to make
// requests to the Zabbix API
type ZabbixDatasource struct {
queryCache *Cache
logger hclog.Logger
httpClient *http.Client
authToken string
}
// NewZabbixDatasource returns an initialized ZabbixDatasource
func NewZabbixDatasource() *ZabbixDatasource {
return &ZabbixDatasource{
queryCache: NewCache(10*time.Minute, 10*time.Minute),
httpClient: &http.Client{
Transport: &http.Transport{ Transport: &http.Transport{
TLSClientConfig: &tls.Config{ TLSClientConfig: &tls.Config{
Renegotiation: tls.RenegotiateFreelyAsClient, Renegotiation: tls.RenegotiateFreelyAsClient,
@@ -28,7 +42,6 @@ var httpClient = &http.Client{
Dial: (&net.Dialer{ Dial: (&net.Dialer{
Timeout: 30 * time.Second, Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second, KeepAlive: 30 * time.Second,
DualStack: true,
}).Dial, }).Dial,
TLSHandshakeTimeout: 10 * time.Second, TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second, ExpectContinueTimeout: 1 * time.Second,
@@ -36,14 +49,13 @@ var httpClient = &http.Client{
IdleConnTimeout: 90 * time.Second, IdleConnTimeout: 90 * time.Second,
}, },
Timeout: time.Duration(time.Second * 30), Timeout: time.Duration(time.Second * 30),
},
}
} }
var queryCache = NewCache(10*time.Minute, 10*time.Minute) // ZabbixAPIQuery handles query requests to Zabbix
var zabbixAuth string = ""
func (ds *ZabbixDatasource) ZabbixAPIQuery(ctx context.Context, tsdbReq *datasource.DatasourceRequest) (*datasource.DatasourceResponse, error) { func (ds *ZabbixDatasource) ZabbixAPIQuery(ctx context.Context, tsdbReq *datasource.DatasourceRequest) (*datasource.DatasourceResponse, error) {
result, queryExistInCache := queryCache.Get(Hash(tsdbReq.String())) result, queryExistInCache := ds.queryCache.Get(HashString(tsdbReq.String()))
if !queryExistInCache { if !queryExistInCache {
dsInfo := tsdbReq.GetDatasource() dsInfo := tsdbReq.GetDatasource()
@@ -86,8 +98,8 @@ func (ds *ZabbixDatasource) ZabbixAPIQuery(ctx context.Context, tsdbReq *datasou
apiMethod := jsonQuery.Get("method").MustString() apiMethod := jsonQuery.Get("method").MustString()
apiParams := jsonQuery.Get("params") apiParams := jsonQuery.Get("params")
result, err = ds.ZabbixRequest(ctx, dsInfo, apiMethod, apiParams) result, err := ds.ZabbixRequest(ctx, dsInfo, apiMethod, apiParams)
queryCache.Set(Hash(tsdbReq.String()), result) ds.queryCache.Set(HashString(tsdbReq.String()), result)
if err != nil { if err != nil {
ds.logger.Debug("ZabbixAPIQuery", "error", err) ds.logger.Debug("ZabbixAPIQuery", "error", err)
return nil, errors.New("ZabbixAPIQuery is not implemented yet") return nil, errors.New("ZabbixAPIQuery is not implemented yet")
@@ -100,6 +112,7 @@ func (ds *ZabbixDatasource) ZabbixAPIQuery(ctx context.Context, tsdbReq *datasou
return ds.BuildResponse(result.(*simplejson.Json)) return ds.BuildResponse(result.(*simplejson.Json))
} }
// BuildResponse transforms a Zabbix API response to a DatasourceResponse
func (ds *ZabbixDatasource) BuildResponse(result *simplejson.Json) (*datasource.DatasourceResponse, error) { func (ds *ZabbixDatasource) BuildResponse(result *simplejson.Json) (*datasource.DatasourceResponse, error) {
resultByte, err := result.MarshalJSON() resultByte, err := result.MarshalJSON()
if err != nil { if err != nil {
@@ -116,19 +129,20 @@ func (ds *ZabbixDatasource) BuildResponse(result *simplejson.Json) (*datasource.
}, nil }, nil
} }
// ZabbixRequest checks authentication and makes a request to the Zabbix API
func (ds *ZabbixDatasource) ZabbixRequest(ctx context.Context, dsInfo *datasource.DatasourceInfo, method string, params *simplejson.Json) (*simplejson.Json, error) { func (ds *ZabbixDatasource) ZabbixRequest(ctx context.Context, dsInfo *datasource.DatasourceInfo, method string, params *simplejson.Json) (*simplejson.Json, error) {
zabbixUrl := dsInfo.GetUrl() zabbixURL := dsInfo.GetUrl()
// Authenticate first // Authenticate first
if zabbixAuth == "" { if ds.authToken == "" {
auth, err := ds.loginWithDs(ctx, dsInfo) auth, err := ds.loginWithDs(ctx, dsInfo)
if err != nil { if err != nil {
return nil, err return nil, err
} }
zabbixAuth = auth ds.authToken = auth
} }
return ds.zabbixAPIRequest(ctx, zabbixUrl, method, params, zabbixAuth) return ds.zabbixAPIRequest(ctx, zabbixURL, method, params, ds.authToken)
} }
func (ds *ZabbixDatasource) loginWithDs(ctx context.Context, dsInfo *datasource.DatasourceInfo) (string, error) { func (ds *ZabbixDatasource) loginWithDs(ctx context.Context, dsInfo *datasource.DatasourceInfo) (string, error) {
@@ -210,7 +224,7 @@ func (ds *ZabbixDatasource) zabbixAPIRequest(ctx context.Context, apiUrl string,
Body: rc, Body: rc,
} }
response, err := makeHttpRequest(ctx, req) response, err := makeHTTPRequest(ctx, ds.httpClient, req)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -233,7 +247,7 @@ func handleApiResult(response []byte) (*simplejson.Json, error) {
return jsonResult, nil return jsonResult, nil
} }
func makeHttpRequest(ctx context.Context, req *http.Request) ([]byte, error) { func makeHTTPRequest(ctx context.Context, httpClient *http.Client, req *http.Request) ([]byte, error) {
res, err := ctxhttp.Do(ctx, httpClient, req) res, err := ctxhttp.Do(ctx, httpClient, req)
if err != nil { if err != nil {
return nil, err return nil, err