diff --git a/pkg/zabbix/methods.go b/pkg/zabbix/methods.go index 6d0737ca5..f65f2b492 100644 --- a/pkg/zabbix/methods.go +++ b/pkg/zabbix/methods.go @@ -2,6 +2,7 @@ package zabbix import ( "context" + "sort" "strconv" "strings" @@ -402,6 +403,13 @@ func (ds *Zabbix) GetAllItems(ctx context.Context, hostids []string, appids []st } tagsParams = append(tagsParams, tagParam) } + // tags order should be handled for higher cache hit ratio + sort.Slice(tagsParams, func(i, j int) bool { + if tagsParams[i]["tag"] != tagsParams[j]["tag"] { + return tagsParams[i]["tag"] < tagsParams[j]["tag"] + } + return tagsParams[i]["value"] < tagsParams[j]["value"] + }) params["tags"] = tagsParams params["evaltype"] = 2 } diff --git a/pkg/zabbix/zabbix_test.go b/pkg/zabbix/zabbix_test.go index 55a9f2003..3e5186498 100644 --- a/pkg/zabbix/zabbix_test.go +++ b/pkg/zabbix/zabbix_test.go @@ -2,6 +2,7 @@ package zabbix import ( "context" + "github.com/alexanderzobnin/grafana-zabbix/pkg/settings" "testing" "github.com/stretchr/testify/assert" @@ -88,3 +89,55 @@ func TestNonCachedQuery(t *testing.T) { result, _ = resp.String() assert.Equal(t, "testNew", result) } + +func TestItemTagCache(t *testing.T) { + zabbixClient, _ := MockZabbixClient( + basicDatasourceInfo, + `{"result":[{"itemid":"1","name":"test1"}]}`, + 200, + ) + // tag filtering is on >= 54 version + zabbixClient.version = 64 + zabbixClient.settings.AuthType = settings.AuthTypeToken + zabbixClient.api.SetAuth("test") + items, err := zabbixClient.GetAllItems( + context.Background(), + nil, + nil, + "num", + false, + "Application: test, interface: test", + ) + + assert.NoError(t, err) + if assert.Len(t, items, 1) { + item := items[0] + assert.Equal(t, "1", item.ID) + assert.Equal(t, "test1", item.Name) + } + + zabbixClient, _ = MockZabbixClientResponse( + zabbixClient, + // intentionally different response to test if the cache hits + `{"result":[{"itemid":"2","name":"test2"}]}`, + 200, + ) + zabbixClient.api.SetAuth("test") + items, err = zabbixClient.GetAllItems( + context.Background(), + nil, + nil, + "num", + false, + // change tag order + "interface: test, Application: test", + ) + + assert.NoError(t, err) + if assert.Len(t, items, 1) { + item := items[0] + // test if it still uses cached response + assert.Equal(t, "1", item.ID) + assert.Equal(t, "test1", item.Name) + } +}