Chore: Upgrade Go to 1.19.1 (#54902)

* WIP

* Set public_suffix to a pre Ruby 2.6 version

* we don't need to install python

* Stretch->Buster

* Bump versions in lib.star

* Manually update linter

Sort of messy, but the .mod-file need to contain all dependencies that
use 1.16+ features, otherwise they're assumed to be compiled with
-lang=go1.16 and cannot access generics et al.

Bingo doesn't seem to understand that, but it's possible to manually
update things to get Bingo happy.

* undo reformatting

* Various lint improvements

* More from the linter

* goimports -w ./pkg/

* Disable gocritic

* Add/modify linter exceptions

* lint + flatten nested list

Go 1.19 doesn't support nested lists, and there wasn't an obvious workaround.
https://go.dev/doc/comment#lists
This commit is contained in:
Emil Tullstedt
2022-09-12 12:03:49 +02:00
committed by GitHub
parent 5388dc6a2f
commit b287047052
91 changed files with 1018 additions and 1055 deletions
+1
View File
@@ -65,6 +65,7 @@ func Download(ctx context.Context, grafanaDir string, p syncutil.WorkerPool) err
pm := m.Plugins[i]
p.Schedule(g.Wrap(func() error {
tgt := filepath.Join(grafanaDir, "plugins-bundled", fmt.Sprintf("%s-%s.zip", pm.Name, pm.Version))
//nolint:gosec
out, err := os.Create(tgt)
if err != nil {
return err
+1
View File
@@ -113,6 +113,7 @@ func BuildManifest(ctx context.Context, dpath string, signingAdmin bool) error {
}
log.Printf("Successfully signed manifest via Grafana API, writing to %q", manifestPath)
//nolint:gosec
f, err := os.Create(manifestPath)
if err != nil {
return fmt.Errorf("failed to create %s: %w", manifestPath, err)
+4
View File
@@ -97,6 +97,10 @@ func RunServer(opt ServerOptions) int {
fmt.Println("diagnostics: pprof profiling enabled", "addr", profileDiagnostics.addr, "port", profileDiagnostics.port)
runtime.SetBlockProfileRate(1)
go func() {
// TODO: We should enable the linter and fix G114 here.
// G114: Use of net/http serve function that has no support for setting timeouts (gosec)
//
//nolint:gosec
err := http.ListenAndServe(fmt.Sprintf("%s:%d", profileDiagnostics.addr, profileDiagnostics.port), nil)
if err != nil {
panic(err)
+7 -6
View File
@@ -6,6 +6,13 @@ package logproto
import (
context "context"
fmt "fmt"
io "io"
math "math"
math_bits "math/bits"
reflect "reflect"
strings "strings"
time "time"
_ "github.com/gogo/protobuf/gogoproto"
proto "github.com/gogo/protobuf/proto"
github_com_gogo_protobuf_types "github.com/gogo/protobuf/types"
@@ -13,12 +20,6 @@ import (
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
io "io"
math "math"
math_bits "math/bits"
reflect "reflect"
strings "strings"
time "time"
)
// Reference imports to suppress errors if they are not otherwise used.
+2 -2
View File
@@ -108,7 +108,7 @@ func (m *Entry) MarshalToSizedBuffer(dAtA []byte) (int, error) {
return len(dAtA) - i, nil
}
//nolint: gocyclo
//nolint:gocyclo
func (m *Stream) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
@@ -248,7 +248,7 @@ func (m *Stream) Unmarshal(dAtA []byte) error {
return nil
}
//nolint: gocyclo
//nolint:gocyclo
func (m *Entry) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
+37 -24
View File
@@ -176,7 +176,8 @@ func (j *Json) Del(key string) {
// for `key` in its `map` representation
//
// useful for chaining operations (to traverse a nested JSON):
// js.Get("top_level").Get("dict").Get("value").Int()
//
// js.Get("top_level").Get("dict").Get("value").Int()
func (j *Json) Get(key string) *Json {
m, err := j.Map()
if err == nil {
@@ -190,7 +191,7 @@ func (j *Json) Get(key string) *Json {
// GetPath searches for the item as specified by the branch
// without the need to deep dive using Get()'s.
//
// js.GetPath("top_level", "dict")
// js.GetPath("top_level", "dict")
func (j *Json) GetPath(branch ...string) *Json {
jin := j
for _, p := range branch {
@@ -204,7 +205,8 @@ func (j *Json) GetPath(branch ...string) *Json {
//
// this is the analog to Get when accessing elements of
// a json array instead of a json object:
// js.Get("top_level").Get("array").GetIndex(1).Get("key").Int()
//
// js.Get("top_level").Get("array").GetIndex(1).Get("key").Int()
func (j *Json) GetIndex(index int) *Json {
a, err := j.Array()
if err == nil {
@@ -220,9 +222,10 @@ func (j *Json) GetIndex(index int) *Json {
// indicating success or failure
//
// useful for chained operations when success is important:
// if data, ok := js.Get("top_level").CheckGetIndex(0); ok {
// log.Println(data)
// }
//
// if data, ok := js.Get("top_level").CheckGetIndex(0); ok {
// log.Println(data)
// }
func (j *Json) CheckGetIndex(index int) (*Json, bool) {
a, err := j.Array()
if err == nil {
@@ -248,9 +251,10 @@ func (j *Json) SetIndex(index int, val interface{}) {
// a `bool` identifying success or failure
//
// useful for chained operations when success is important:
// if data, ok := js.Get("top_level").CheckGet("inner"); ok {
// log.Println(data)
// }
//
// if data, ok := js.Get("top_level").CheckGet("inner"); ok {
// log.Println(data)
// }
func (j *Json) CheckGet(key string) (*Json, bool) {
m, err := j.Map()
if err == nil {
@@ -325,9 +329,10 @@ func (j *Json) StringArray() ([]string, error) {
// MustArray guarantees the return of a `[]interface{}` (with optional default)
//
// useful when you want to iterate over array values in a succinct manner:
// for i, v := range js.Get("results").MustArray() {
// fmt.Println(i, v)
// }
//
// for i, v := range js.Get("results").MustArray() {
// fmt.Println(i, v)
// }
func (j *Json) MustArray(args ...[]interface{}) []interface{} {
var def []interface{}
@@ -350,9 +355,10 @@ func (j *Json) MustArray(args ...[]interface{}) []interface{} {
// MustMap guarantees the return of a `map[string]interface{}` (with optional default)
//
// useful when you want to iterate over map values in a succinct manner:
// for k, v := range js.Get("dictionary").MustMap() {
// fmt.Println(k, v)
// }
//
// for k, v := range js.Get("dictionary").MustMap() {
// fmt.Println(k, v)
// }
func (j *Json) MustMap(args ...map[string]interface{}) map[string]interface{} {
var def map[string]interface{}
@@ -375,7 +381,8 @@ func (j *Json) MustMap(args ...map[string]interface{}) map[string]interface{} {
// MustString guarantees the return of a `string` (with optional default)
//
// useful when you explicitly want a `string` in a single value return context:
// myFunc(js.Get("param1").MustString(), js.Get("optional_param").MustString("my_default"))
//
// myFunc(js.Get("param1").MustString(), js.Get("optional_param").MustString("my_default"))
func (j *Json) MustString(args ...string) string {
var def string
@@ -398,9 +405,10 @@ func (j *Json) MustString(args ...string) string {
// MustStringArray guarantees the return of a `[]string` (with optional default)
//
// useful when you want to iterate over array values in a succinct manner:
// for i, s := range js.Get("results").MustStringArray() {
// fmt.Println(i, s)
// }
//
// for i, s := range js.Get("results").MustStringArray() {
// fmt.Println(i, s)
// }
func (j *Json) MustStringArray(args ...[]string) []string {
var def []string
@@ -423,7 +431,8 @@ func (j *Json) MustStringArray(args ...[]string) []string {
// MustInt guarantees the return of an `int` (with optional default)
//
// useful when you explicitly want an `int` in a single value return context:
// myFunc(js.Get("param1").MustInt(), js.Get("optional_param").MustInt(5150))
//
// myFunc(js.Get("param1").MustInt(), js.Get("optional_param").MustInt(5150))
func (j *Json) MustInt(args ...int) int {
var def int
@@ -446,7 +455,8 @@ func (j *Json) MustInt(args ...int) int {
// MustFloat64 guarantees the return of a `float64` (with optional default)
//
// useful when you explicitly want a `float64` in a single value return context:
// myFunc(js.Get("param1").MustFloat64(), js.Get("optional_param").MustFloat64(5.150))
//
// myFunc(js.Get("param1").MustFloat64(), js.Get("optional_param").MustFloat64(5.150))
func (j *Json) MustFloat64(args ...float64) float64 {
var def float64
@@ -469,7 +479,8 @@ func (j *Json) MustFloat64(args ...float64) float64 {
// MustBool guarantees the return of a `bool` (with optional default)
//
// useful when you explicitly want a `bool` in a single value return context:
// myFunc(js.Get("param1").MustBool(), js.Get("optional_param").MustBool(true))
//
// myFunc(js.Get("param1").MustBool(), js.Get("optional_param").MustBool(true))
func (j *Json) MustBool(args ...bool) bool {
var def bool
@@ -492,7 +503,8 @@ func (j *Json) MustBool(args ...bool) bool {
// MustInt64 guarantees the return of an `int64` (with optional default)
//
// useful when you explicitly want an `int64` in a single value return context:
// myFunc(js.Get("param1").MustInt64(), js.Get("optional_param").MustInt64(5150))
//
// myFunc(js.Get("param1").MustInt64(), js.Get("optional_param").MustInt64(5150))
func (j *Json) MustInt64(args ...int64) int64 {
var def int64
@@ -515,7 +527,8 @@ func (j *Json) MustInt64(args ...int64) int64 {
// MustUInt64 guarantees the return of an `uint64` (with optional default)
//
// useful when you explicitly want an `uint64` in a single value return context:
// myFunc(js.Get("param1").MustUint64(), js.Get("optional_param").MustUint64(5150))
//
// myFunc(js.Get("param1").MustUint64(), js.Get("optional_param").MustUint64(5150))
func (j *Json) MustUint64(args ...uint64) uint64 {
var def uint64
+1 -1
View File
@@ -62,7 +62,7 @@ func themaTestableDashboards(in fs.FS) (map[string][]byte, error) {
if err != nil {
return err
}
defer f.Close() // nolint: errcheck
defer f.Close() //nolint:errcheck
b, err := io.ReadAll(f)
if err != nil {
+1 -1
View File
@@ -21,7 +21,7 @@ func (cr classicReducer) ValidReduceFunc() bool {
return false
}
//nolint: gocyclo
//nolint:gocyclo
func (cr classicReducer) Reduce(series mathexp.Series) mathexp.Number {
num := mathexp.NewNumber("", nil)
+1
View File
@@ -1,4 +1,5 @@
// Package gcsifaces provides interfaces for Google Cloud Storage.
//
//go:generate mockgen -source $GOFILE -destination ../../mocks/mock_gcsifaces/mocks.go StorageClient
package gcsifaces
@@ -7,11 +7,12 @@ import (
"io"
"strings"
"github.com/grafana/grafana/pkg/infra/log"
"gocloud.dev/blob"
_ "gocloud.dev/blob/fileblob"
_ "gocloud.dev/blob/memblob"
"gocloud.dev/gcerrors"
"github.com/grafana/grafana/pkg/infra/log"
)
const (
@@ -282,7 +283,7 @@ func (c cdkBlobStorage) DeleteFolder(ctx context.Context, folderPath string, opt
return lastErr
}
//nolint: gocyclo
//nolint:gocyclo
func (c cdkBlobStorage) list(ctx context.Context, folderPath string, paging *Paging, options *ListOptions) (*ListResponse, error) {
lowerRootPath := strings.ToLower(folderPath)
iterators := []*blob.ListIterator{c.bucket.List(&blob.ListOptions{
+1 -1
View File
@@ -284,7 +284,7 @@ func upsertProperty(dialect migrator.Dialect, sess *sqlstore.DBSession, now time
return err
}
//nolint: gocyclo
//nolint:gocyclo
func (s dbFileStorage) List(ctx context.Context, folderPath string, paging *Paging, options *ListOptions) (*ListResponse, error) {
var resp *ListResponse
+1
View File
@@ -75,6 +75,7 @@ func copyFileContents(src, dst string) (err error) {
}
}()
//nolint:gosec
out, err := os.Create(dst)
if err != nil {
return
+1 -1
View File
@@ -11,7 +11,7 @@ var dbCallCounterNameKey = contextKey{}
// InitCounter creates a pointer on the context that can be incremented later
func InitCounter(ctx context.Context) context.Context {
var ptr *int64 = new(int64)
var ptr = new(int64)
return context.WithValue(ctx, dbCallCounterNameKey, ptr)
}
+2 -3
View File
@@ -34,12 +34,11 @@ type terminalLogger struct {
// level output and terser human friendly timestamp.
// This format should only be used for interactive programs or while developing.
//
// [TIME] [LEVEL] MESSAGE key=value key=value ...
// [TIME] [LEVEL] MESSAGE key=value key=value ...
//
// Example:
//
// [May 16 20:58:45] [DBUG] remove route ns=haproxy addr=127.0.0.1:50002
//
// [May 16 20:58:45] [DBUG] remove route ns=haproxy addr=127.0.0.1:50002
func NewTerminalLogger(w io.Writer) gokitlog.Logger {
return &terminalLogger{w}
}
+2 -1
View File
@@ -8,6 +8,7 @@ import (
"time"
"github.com/go-kit/log"
glog "github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/registry"
"github.com/grafana/grafana/pkg/services/sqlstore"
@@ -45,7 +46,7 @@ func ProvideService(cfg *setting.Cfg, sqlStore *sqlstore.SQLStore) (*RemoteCache
// CacheStorage allows the caller to set, get and delete items in the cache.
// Cached items are stored as byte arrays and marshalled using "encoding/gob"
// so any struct added to the cache needs to be registered with `remotecache.Register`
// ex `remotecache.Register(CacheableStruct{})``
// ex `remotecache.Register(CacheableStruct{})`
type CacheStorage interface {
// Get reads object from Cache
Get(ctx context.Context, key string) (interface{}, error)
-2
View File
@@ -98,9 +98,7 @@ func (dto *DashboardACLInfoDTO) IsDuplicateOf(other *DashboardACLInfoDTO) bool {
return dto.hasSameRoleAs(other) || dto.hasSameUserAs(other) || dto.hasSameTeamAs(other)
}
//
// QUERIES
//
type GetDashboardACLInfoListQuery struct {
DashboardID int64
OrgID int64
@@ -8,13 +8,14 @@ package pluginextensionv2
import (
context "context"
reflect "reflect"
sync "sync"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
@@ -8,13 +8,14 @@ package pluginextensionv2
import (
context "context"
reflect "reflect"
sync "sync"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
@@ -7,10 +7,11 @@
package secretsmanagerplugin
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
)
const (
@@ -8,6 +8,7 @@ package secretsmanagerplugin
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
+2
View File
@@ -51,6 +51,7 @@ func TestAdd(t *testing.T) {
func TestRemove(t *testing.T) {
pluginDir := t.TempDir()
pluginJSON := filepath.Join(pluginDir, "plugin.json")
//nolint:gosec
_, err := os.Create(pluginJSON)
require.NoError(t, err)
@@ -74,6 +75,7 @@ func TestRemove(t *testing.T) {
err = os.Mkdir(pluginDistDir, os.ModePerm)
require.NoError(t, err)
pluginJSON = filepath.Join(pluginDistDir, "plugin.json")
//nolint:gosec
_, err = os.Create(pluginJSON)
require.NoError(t, err)
@@ -127,7 +127,7 @@ type fakeIntervalTestReqHandler struct {
verifier queryIntervalVerifier
}
//nolint: staticcheck // legacydata.DataResponse deprecated
//nolint:staticcheck // legacydata.DataResponse deprecated
func (rh fakeIntervalTestReqHandler) HandleRequest(ctx context.Context, dsInfo *datasources.DataSource, query legacydata.DataQuery) (
legacydata.DataResponse, error) {
q := query.Queries[0]
@@ -135,7 +135,7 @@ func (rh fakeIntervalTestReqHandler) HandleRequest(ctx context.Context, dsInfo *
return rh.response, nil
}
//nolint: staticcheck // legacydata.DataResponse deprecated
//nolint:staticcheck // legacydata.DataResponse deprecated
func applyScenario(t *testing.T, timeRange string, dataSourceJsonData *simplejson.Json, queryModel string, verifier func(query legacydata.DataSubQuery)) {
t.Run("desc", func(t *testing.T) {
store := mockstore.NewSQLStoreMock()
@@ -210,7 +210,7 @@ type queryConditionTestContext struct {
condition *QueryCondition
}
//nolint: staticcheck // legacydata.DataPlugin deprecated
//nolint:staticcheck // legacydata.DataPlugin deprecated
func (ctx *queryConditionTestContext) exec(t *testing.T) (*alerting.ConditionResult, error) {
jsonModel, err := simplejson.NewJson([]byte(`{
"type": "query",
@@ -254,7 +254,7 @@ type fakeReqHandler struct {
response legacydata.DataResponse
}
//nolint: staticcheck // legacydata.DataPlugin deprecated
//nolint:staticcheck // legacydata.DataPlugin deprecated
func (rh fakeReqHandler) HandleRequest(context.Context, *datasources.DataSource, legacydata.DataQuery) (
legacydata.DataResponse, error) {
return rh.response, nil
+1 -1
View File
@@ -17,7 +17,7 @@ type queryReducer struct {
Type string
}
//nolint: gocyclo
//nolint:gocyclo
func (s *queryReducer) Reduce(series legacydata.DataTimeSeries) null.Float {
if len(series.Points) == 0 {
return null.FloatFromPtr(nil)
+2 -1
View File
@@ -17,7 +17,8 @@ import (
)
// for stubbing in tests
//nolint: gocritic
//
//nolint:gocritic
var newImageUploaderProvider = func() (imguploader.ImageUploader, error) {
return imguploader.NewImageUploader()
}
@@ -54,7 +54,8 @@ type GoogleChatNotifier struct {
log log.Logger
}
/**
/*
*
Structs used to build a custom Google Hangouts Chat message card.
See: https://developers.google.com/hangouts/chat/reference/message-formats/cards
*/
+4 -4
View File
@@ -11,10 +11,10 @@ import (
)
// Ticker is a ticker to power the alerting scheduler. it's like a time.Ticker, except:
// * it doesn't drop ticks for slow receivers, rather, it queues up. so that callers are in control to instrument what's going on.
// * it ticks on interval marks or very shortly after. this provides a predictable load pattern
// (this shouldn't cause too much load contention issues because the next steps in the pipeline just process at their own pace)
// * the timestamps are used to mark "last datapoint to query for" and as such, are a configurable amount of seconds in the past
// - it doesn't drop ticks for slow receivers, rather, it queues up. so that callers are in control to instrument what's going on.
// - it ticks on interval marks or very shortly after. this provides a predictable load pattern
// (this shouldn't cause too much load contention issues because the next steps in the pipeline just process at their own pace)
// - the timestamps are used to mark "last datapoint to query for" and as such, are a configurable amount of seconds in the past
type Ticker struct {
C chan time.Time
clock clock.Clock
+6 -5
View File
@@ -6,8 +6,9 @@ import (
"reflect"
"time"
"github.com/grafana/grafana/pkg/models"
"gopkg.in/square/go-jose.v2/jwt"
"github.com/grafana/grafana/pkg/models"
)
func (s *AuthService) initClaimExpectations() error {
@@ -35,8 +36,8 @@ func (s *AuthService) initClaimExpectations() error {
switch value := value.(type) {
case []interface{}:
for _, val := range value {
if val, ok := val.(string); ok {
s.expectRegistered.Audience = append(s.expectRegistered.Audience, val)
if v, ok := val.(string); ok {
s.expectRegistered.Audience = append(s.expectRegistered.Audience, v)
} else {
return fmt.Errorf("%q expectation contains value with invalid type %T, string expected", key, val)
}
@@ -73,8 +74,8 @@ func (s *AuthService) validateClaims(claims models.JWTClaims) error {
switch value := value.(type) {
case []interface{}:
for _, val := range value {
if val, ok := val.(string); ok {
registeredClaims.Audience = append(registeredClaims.Audience, val)
if v, ok := val.(string); ok {
registeredClaims.Audience = append(registeredClaims.Audience, v)
} else {
return fmt.Errorf("%q claim contains value with invalid type %T, string expected", key, val)
}
+8 -4
View File
@@ -6,8 +6,9 @@ import (
"github.com/grafana/grafana/pkg/models"
)
//go:generate mockery --name DashboardService --structname FakeDashboardService --inpackage --filename dashboard_service_mock.go
// DashboardService is a service for operating on dashboards.
//
//go:generate mockery --name DashboardService --structname FakeDashboardService --inpackage --filename dashboard_service_mock.go
type DashboardService interface {
BuildSaveDashboardCommand(ctx context.Context, dto *SaveDashboardDTO, shouldValidateAlerts bool, validateProvisionedDashboard bool) (*models.SaveDashboardCommand, error)
DeleteDashboard(ctx context.Context, dashboardId int64, orgId int64) error
@@ -32,8 +33,9 @@ type PluginService interface {
GetDashboardsByPluginID(ctx context.Context, query *models.GetDashboardsByPluginIdQuery) error
}
//go:generate mockery --name DashboardProvisioningService --structname FakeDashboardProvisioning --inpackage --filename dashboard_provisioning_mock.go
// DashboardProvisioningService is a service for operating on provisioned dashboards.
//
//go:generate mockery --name DashboardProvisioningService --structname FakeDashboardProvisioning --inpackage --filename dashboard_provisioning_mock.go
type DashboardProvisioningService interface {
DeleteOrphanedProvisionedDashboards(ctx context.Context, cmd *models.DeleteOrphanedProvisionedDashboardsCommand) error
DeleteProvisionedDashboard(ctx context.Context, dashboardID int64, orgID int64) error
@@ -45,8 +47,9 @@ type DashboardProvisioningService interface {
UnprovisionDashboard(ctx context.Context, dashboardID int64) error
}
//go:generate mockery --name Store --structname FakeDashboardStore --inpackage --filename store_mock.go
// Store is a dashboard store.
//
//go:generate mockery --name Store --structname FakeDashboardStore --inpackage --filename store_mock.go
type Store interface {
DeleteDashboard(ctx context.Context, cmd *models.DeleteDashboardCommand) error
DeleteOrphanedProvisionedDashboards(ctx context.Context, cmd *models.DeleteOrphanedProvisionedDashboardsCommand) error
@@ -76,8 +79,9 @@ type Store interface {
FolderStore
}
//go:generate mockery --name FolderStore --structname FakeFolderStore --inpackage --filename folder_store_mock.go
// FolderStore is a folder store.
//
//go:generate mockery --name FolderStore --structname FakeFolderStore --inpackage --filename folder_store_mock.go
type FolderStore interface {
// GetFolderByTitle retrieves a folder by its title
GetFolderByTitle(ctx context.Context, orgID int64, title string) (*models.Folder, error)
+2 -1
View File
@@ -7,8 +7,9 @@ import (
"github.com/grafana/grafana/pkg/services/user"
)
//go:generate mockery --name FolderService --structname FakeFolderService --inpackage --filename folder_service_mock.go
// FolderService is a service for operating on folders.
//
//go:generate mockery --name FolderService --structname FakeFolderService --inpackage --filename folder_service_mock.go
type FolderService interface {
GetFolders(ctx context.Context, user *user.SignedInUser, orgID int64, limit int64, page int64) ([]*models.Folder, error)
GetFolderByID(ctx context.Context, user *user.SignedInUser, id int64, orgID int64) (*models.Folder, error)
+2 -1
View File
@@ -65,7 +65,8 @@ func ToDelimited(s string, delimiter uint8) string {
// (in this case `delimiter = '.'; screaming = true`)
// or delimited.snake.case
// (in this case `delimiter = '.'; screaming = false`)
//nolint: gocyclo
//
//nolint:gocyclo
func ToScreamingDelimited(s string, delimiter uint8, ignore string, screaming bool) string {
s = strings.TrimSpace(s)
n := strings.Builder{}
@@ -3,23 +3,22 @@
// Package definitions includes the types required for generating or consuming an OpenAPI
// spec for the Grafana Alerting API.
//
// Schemes: http, https
// BasePath: /api/v1
// Version: 1.1.0
//
// Schemes: http, https
// BasePath: /api/v1
// Version: 1.1.0
// Consumes:
// - application/json
//
// Consumes:
// - application/json
// Produces:
// - application/json
//
// Produces:
// - application/json
// Security:
// - basic
//
// Security:
// - basic
//
// SecurityDefinitions:
// basic:
// type: basic
// SecurityDefinitions:
// basic:
// type: basic
//
// swagger:meta
package definitions
+18 -15
View File
@@ -331,18 +331,18 @@ func executeQueriesAndExpressions(ctx AlertExecCtx, data []models.AlertQuery, no
//
// For example, given the following:
//
// map[string]string{
// "ref1": "datasource1",
// "ref2": "datasource1",
// "ref3": "datasource2",
// }
// map[string]string{
// "ref1": "datasource1",
// "ref2": "datasource1",
// "ref3": "datasource2",
// }
//
// we would expect:
//
// map[string][]string{
// "datasource1": []string{"ref1", "ref2"},
// "datasource2": []string{"ref3"},
// }
// map[string][]string{
// "datasource1": []string{"ref1", "ref2"},
// "datasource2": []string{"ref3"},
// }
func datasourceUIDsToRefIDs(refIDsToDatasourceUIDs map[string]string) map[string][]string {
if refIDsToDatasourceUIDs == nil {
return nil
@@ -377,12 +377,15 @@ func datasourceUIDsToRefIDs(refIDsToDatasourceUIDs map[string]string) map[string
// Also, each Frame must be uniquely identified by its Field.Labels or a single Error result will be returned.
//
// Per Frame, data becomes a State based on the following rules:
// - Empty or zero length Frames result in NoData.
// - If a value:
// - 0 results in Normal.
// - Nonzero (e.g 1.2, NaN) results in Alerting.
// - nil results in noData.
// - unsupported Frame schemas results in Error.
//
// If no value is set:
// - Empty or zero length Frames result in NoData.
//
// If a value is set:
// - 0 results in Normal.
// - Nonzero (e.g 1.2, NaN) results in Alerting.
// - nil results in noData.
// - unsupported Frame schemas results in Error.
func evaluateExecutionResult(execResults ExecutionResults, ts time.Time) Results {
evalResults := make([]Result, 0)
+5 -5
View File
@@ -48,8 +48,8 @@ type FakeEvaluator_ConditionEval_Call struct {
}
// ConditionEval is a helper method to define mock.On call
// - condition models.Condition
// - now time.Time
// - condition models.Condition
// - now time.Time
func (_e *FakeEvaluator_Expecter) ConditionEval(condition interface{}, now interface{}) *FakeEvaluator_ConditionEval_Call {
return &FakeEvaluator_ConditionEval_Call{Call: _e.mock.On("ConditionEval", condition, now)}
}
@@ -95,9 +95,9 @@ type FakeEvaluator_QueriesAndExpressionsEval_Call struct {
}
// QueriesAndExpressionsEval is a helper method to define mock.On call
// - orgID int64
// - data []models.AlertQuery
// - now time.Time
// - orgID int64
// - data []models.AlertQuery
// - now time.Time
func (_e *FakeEvaluator_Expecter) QueriesAndExpressionsEval(orgID interface{}, data interface{}, now interface{}) *FakeEvaluator_QueriesAndExpressionsEval_Call {
return &FakeEvaluator_QueriesAndExpressionsEval_Call{Call: _e.mock.On("QueriesAndExpressionsEval", orgID, data, now)}
}
@@ -110,11 +110,12 @@ func newTestImage() (string, error) {
// mockTimeNow replaces function timeNow to return constant time.
// It returns a function that resets the variable back to its original value.
// This allows usage of this function with defer:
// func Test (t *testing.T) {
// now := time.Now()
// defer mockTimeNow(now)()
// ...
// }
//
// func Test (t *testing.T) {
// now := time.Now()
// defer mockTimeNow(now)()
// ...
// }
func mockTimeNow(constTime time.Time) func() {
timeNow = func() time.Time {
return constTime
@@ -96,6 +96,7 @@ func withStoredImages(ctx context.Context, l log.Logger, imageStore ImageStore,
// The path argument here comes from reading internal image storage, not user
// input, so we ignore the security check here.
//
//nolint:gosec
func openImage(path string) (io.ReadCloser, error) {
fp := filepath.Clean(path)
@@ -12,6 +12,7 @@ import (
)
// AMStore is a store of Alertmanager configurations.
//
//go:generate mockery --name AMConfigStore --structname MockAMConfigStore --inpackage --filename persist_mock.go --with-expecter
type AMConfigStore interface {
GetLatestAlertmanagerConfiguration(ctx context.Context, query *models.GetLatestAlertmanagerConfigurationQuery) error
@@ -19,6 +20,7 @@ type AMConfigStore interface {
}
// ProvisioningStore is a store of provisioning data for arbitrary objects.
//
//go:generate mockery --name ProvisioningStore --structname MockProvisioningStore --inpackage --filename provisioning_store_mock.go --with-expecter
type ProvisioningStore interface {
GetProvenance(ctx context.Context, o models.Provisionable, org int64) (models.Provenance, error)
@@ -44,6 +46,7 @@ type RuleStore interface {
}
// QuotaChecker represents the ability to evaluate whether quotas are met.
//
//go:generate mockery --name QuotaChecker --structname MockQuotaChecker --inpackage --filename quota_checker_mock.go --with-expecter
type QuotaChecker interface {
CheckQuotaReached(ctx context.Context, target string, scopeParams *quota.ScopeParameters) (bool, error)
@@ -44,8 +44,8 @@ type MockAMConfigStore_GetLatestAlertmanagerConfiguration_Call struct {
}
// GetLatestAlertmanagerConfiguration is a helper method to define mock.On call
// - ctx context.Context
// - query *models.GetLatestAlertmanagerConfigurationQuery
// - ctx context.Context
// - query *models.GetLatestAlertmanagerConfigurationQuery
func (_e *MockAMConfigStore_Expecter) GetLatestAlertmanagerConfiguration(ctx interface{}, query interface{}) *MockAMConfigStore_GetLatestAlertmanagerConfiguration_Call {
return &MockAMConfigStore_GetLatestAlertmanagerConfiguration_Call{Call: _e.mock.On("GetLatestAlertmanagerConfiguration", ctx, query)}
}
@@ -82,8 +82,8 @@ type MockAMConfigStore_UpdateAlertmanagerConfiguration_Call struct {
}
// UpdateAlertmanagerConfiguration is a helper method to define mock.On call
// - ctx context.Context
// - cmd *models.SaveAlertmanagerConfigurationCmd
// - ctx context.Context
// - cmd *models.SaveAlertmanagerConfigurationCmd
func (_e *MockAMConfigStore_Expecter) UpdateAlertmanagerConfiguration(ctx interface{}, cmd interface{}) *MockAMConfigStore_UpdateAlertmanagerConfiguration_Call {
return &MockAMConfigStore_UpdateAlertmanagerConfiguration_Call{Call: _e.mock.On("UpdateAlertmanagerConfiguration", ctx, cmd)}
}
@@ -44,9 +44,9 @@ type MockProvisioningStore_DeleteProvenance_Call struct {
}
// DeleteProvenance is a helper method to define mock.On call
// - ctx context.Context
// - o models.Provisionable
// - org int64
// - ctx context.Context
// - o models.Provisionable
// - org int64
func (_e *MockProvisioningStore_Expecter) DeleteProvenance(ctx interface{}, o interface{}, org interface{}) *MockProvisioningStore_DeleteProvenance_Call {
return &MockProvisioningStore_DeleteProvenance_Call{Call: _e.mock.On("DeleteProvenance", ctx, o, org)}
}
@@ -90,9 +90,9 @@ type MockProvisioningStore_GetProvenance_Call struct {
}
// GetProvenance is a helper method to define mock.On call
// - ctx context.Context
// - o models.Provisionable
// - org int64
// - ctx context.Context
// - o models.Provisionable
// - org int64
func (_e *MockProvisioningStore_Expecter) GetProvenance(ctx interface{}, o interface{}, org interface{}) *MockProvisioningStore_GetProvenance_Call {
return &MockProvisioningStore_GetProvenance_Call{Call: _e.mock.On("GetProvenance", ctx, o, org)}
}
@@ -138,9 +138,9 @@ type MockProvisioningStore_GetProvenances_Call struct {
}
// GetProvenances is a helper method to define mock.On call
// - ctx context.Context
// - org int64
// - resourceType string
// - ctx context.Context
// - org int64
// - resourceType string
func (_e *MockProvisioningStore_Expecter) GetProvenances(ctx interface{}, org interface{}, resourceType interface{}) *MockProvisioningStore_GetProvenances_Call {
return &MockProvisioningStore_GetProvenances_Call{Call: _e.mock.On("GetProvenances", ctx, org, resourceType)}
}
@@ -177,10 +177,10 @@ type MockProvisioningStore_SetProvenance_Call struct {
}
// SetProvenance is a helper method to define mock.On call
// - ctx context.Context
// - o models.Provisionable
// - org int64
// - p models.Provenance
// - ctx context.Context
// - o models.Provisionable
// - org int64
// - p models.Provenance
func (_e *MockProvisioningStore_Expecter) SetProvenance(ctx interface{}, o interface{}, org interface{}, p interface{}) *MockProvisioningStore_SetProvenance_Call {
return &MockProvisioningStore_SetProvenance_Call{Call: _e.mock.On("SetProvenance", ctx, o, org, p)}
}
@@ -51,9 +51,9 @@ type MockQuotaChecker_CheckQuotaReached_Call struct {
}
// CheckQuotaReached is a helper method to define mock.On call
// - ctx context.Context
// - target string
// - scopeParams *quota.ScopeParameters
// - ctx context.Context
// - target string
// - scopeParams *quota.ScopeParameters
func (_e *MockQuotaChecker_Expecter) CheckQuotaReached(ctx interface{}, target interface{}, scopeParams interface{}) *MockQuotaChecker_CheckQuotaReached_Call {
return &MockQuotaChecker_CheckQuotaReached_Call{Call: _e.mock.On("CheckQuotaReached", ctx, target, scopeParams)}
}
@@ -33,8 +33,8 @@ type AlertsSenderMock_Send_Call struct {
}
// Send is a helper method to define mock.On call
// - key models.AlertRuleKey
// - alerts definitions.PostableAlerts
// - key models.AlertRuleKey
// - alerts definitions.PostableAlerts
func (_e *AlertsSenderMock_Expecter) Send(key interface{}, alerts interface{}) *AlertsSenderMock_Send_Call {
return &AlertsSenderMock_Send_Call{Call: _e.mock.On("Send", key, alerts)}
}
@@ -252,7 +252,7 @@ func assertEvalRun(t *testing.T, ch <-chan evalAppliedInfo, tick time.Time, keys
case info := <-ch:
_, ok := expected[info.alertDefKey]
if !ok {
t.Fatal(fmt.Sprintf("alert rule: %v should not have been evaluated at: %v", info.alertDefKey, info.now))
t.Fatalf("alert rule: %v should not have been evaluated at: %v", info.alertDefKey, info.now)
}
t.Logf("alert rule: %v evaluated at: %v", info.alertDefKey, info.now)
assert.Equal(t, tick, info.now)
@@ -40,7 +40,7 @@ type AdminConfigurationStoreMock_DeleteAdminConfiguration_Call struct {
}
// DeleteAdminConfiguration is a helper method to define mock.On call
// - orgID int64
// - orgID int64
func (_e *AdminConfigurationStoreMock_Expecter) DeleteAdminConfiguration(orgID interface{}) *AdminConfigurationStoreMock_DeleteAdminConfiguration_Call {
return &AdminConfigurationStoreMock_DeleteAdminConfiguration_Call{Call: _e.mock.On("DeleteAdminConfiguration", orgID)}
}
@@ -86,7 +86,7 @@ type AdminConfigurationStoreMock_GetAdminConfiguration_Call struct {
}
// GetAdminConfiguration is a helper method to define mock.On call
// - orgID int64
// - orgID int64
func (_e *AdminConfigurationStoreMock_Expecter) GetAdminConfiguration(orgID interface{}) *AdminConfigurationStoreMock_GetAdminConfiguration_Call {
return &AdminConfigurationStoreMock_GetAdminConfiguration_Call{Call: _e.mock.On("GetAdminConfiguration", orgID)}
}
@@ -168,7 +168,7 @@ type AdminConfigurationStoreMock_UpdateAdminConfiguration_Call struct {
}
// UpdateAdminConfiguration is a helper method to define mock.On call
// - _a0 UpdateAdminConfigurationCmd
// - _a0 UpdateAdminConfigurationCmd
func (_e *AdminConfigurationStoreMock_Expecter) UpdateAdminConfiguration(_a0 interface{}) *AdminConfigurationStoreMock_UpdateAdminConfiguration_Call {
return &AdminConfigurationStoreMock_UpdateAdminConfiguration_Call{Call: _e.mock.On("UpdateAdminConfiguration", _a0)}
}
+1 -1
View File
@@ -85,7 +85,7 @@ func (s *Service) DeleteUserFromAll(ctx context.Context, userID int64) error {
return s.store.DeleteUserFromAll(ctx, userID)
}
// TODO: remove wrapper around sqlstore
// TODO: remove wrapper around sqlstore
func (s *Service) GetUserOrgList(ctx context.Context, query *org.GetUserOrgListQuery) ([]*org.UserOrgDTO, error) {
q := &models.GetUserOrgListQuery{
UserId: query.UserID,
+5 -4
View File
@@ -1,13 +1,14 @@
// Package values is a set of value types to use in provisioning. They add custom unmarshaling logic that puts the string values
// through os.ExpandEnv.
// Usage:
// type Data struct {
// Field StringValue `yaml:"field"` // Instead of string
// }
//
// type Data struct {
// Field StringValue `yaml:"field"` // Instead of string
// }
//
// d := &Data{}
// // unmarshal into d
// d.Field.Value() // returns the final interpolated value from the yaml file
//
package values
import (
+1 -1
View File
@@ -48,7 +48,7 @@ func ProvideApi(
return api
}
//Registers Endpoints on Grafana Router
// Registers Endpoints on Grafana Router
func (api *Api) RegisterAPIEndpoints() {
auth := accesscontrol.Middleware(api.AccessControl)
@@ -363,7 +363,7 @@ func TestApiSavePublicDashboardConfig(t *testing.T) {
}
}
// `/public/dashboards/:uid/query`` endpoint test
// `/public/dashboards/:uid/query“ endpoint test
func TestAPIQueryPublicDashboard(t *testing.T) {
mockedResponse := &backend.QueryDataResponse{
Responses: map[string]backend.DataResponse{
@@ -101,9 +101,7 @@ func (pd PublicDashboard) BuildTimeSettings(dashboard *models.Dashboard) TimeSet
return ts
}
//
// DTO for transforming user input in the api
//
type SavePublicDashboardConfigDTO struct {
DashboardUid string
OrgId int64
+1
View File
@@ -175,6 +175,7 @@ func (rs *RenderingService) readFileResponse(ctx context.Context, resp *http.Res
resp.Status)
}
//nolint:gosec
out, err := os.Create(filePath)
if err != nil {
return err
+1
View File
@@ -78,6 +78,7 @@ func (s ScreenshotOptions) SetDefaults() ScreenshotOptions {
}
// ScreenshotService is an interface for taking screenshots.
//
//go:generate mockgen -destination=mock.go -package=screenshot github.com/grafana/grafana/pkg/services/screenshot ScreenshotService
type ScreenshotService interface {
Take(ctx context.Context, opts ScreenshotOptions) (*Screenshot, error)
+2 -1
View File
@@ -13,6 +13,7 @@ import (
"github.com/blugelabs/bluge/search/aggregations"
"github.com/grafana/grafana-plugin-sdk-go/backend"
"github.com/grafana/grafana-plugin-sdk-go/data"
"github.com/grafana/grafana/pkg/infra/log"
)
@@ -349,7 +350,7 @@ func getDashboardLocation(index *orgIndex, dashboardUID string) (string, bool, e
return dashboardLocation, found, err
}
//nolint: gocyclo
//nolint:gocyclo
func doSearchQuery(
ctx context.Context,
logger log.Logger,
@@ -8,9 +8,10 @@ import (
"strings"
"testing"
"github.com/grafana/grafana/pkg/services/searchV2/dslookup"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/services/searchV2/dslookup"
)
func dsLookup() dslookup.DatasourceLookup {
@@ -98,6 +99,7 @@ func TestReadDashboard(t *testing.T) {
update := false
savedPath := filepath.Join("testdata/", input+"-info.json")
//nolint:gosec
saved, err := os.ReadFile(savedPath)
if err != nil {
update = true
@@ -199,6 +199,7 @@ func openReplace(filename string) (*replaceFile, error) {
return nil, err
}
//nolint:gosec
f, err := os.Create(tmpFilename)
if err != nil {
return nil, err
@@ -232,7 +232,7 @@ func (m *migration) SQL(dialect migrator.Dialect) string {
return codeMigration
}
// nolint: gocyclo
//nolint:gocyclo
func (m *migration) Exec(sess *xorm.Session, mg *migrator.Migrator) error {
m.sess = sess
m.mg = mg
+1 -1
View File
@@ -313,7 +313,7 @@ func (b *BaseDialect) TruncateDBTables() error {
return nil
}
//UpsertSQL returns empty string
// UpsertSQL returns empty string
func (b *BaseDialect) UpsertSQL(tableName string, keyCols, updateCols []string) string {
return ""
}
+2 -2
View File
@@ -416,7 +416,7 @@ func TestIntegrationAccountDataAccess(t *testing.T) {
})
}
//TODO: Use FakeDashboardStore when org has its own service
// TODO: Use FakeDashboardStore when org has its own service
func insertTestDashboard(t *testing.T, sqlStore *SQLStore, title string, orgId int64,
folderId int64, isFolder bool, tags ...interface{}) *models.Dashboard {
t.Helper()
@@ -473,7 +473,7 @@ func insertTestDashboard(t *testing.T, sqlStore *SQLStore, title string, orgId i
return dash
}
//TODO: Use FakeDashboardStore when org has its own service
// TODO: Use FakeDashboardStore when org has its own service
func updateDashboardACL(t *testing.T, sqlStore *SQLStore, dashboardID int64, items ...*models.DashboardACL) error {
t.Helper()
+5 -5
View File
@@ -21,11 +21,11 @@
//
// Filters will be applied in order with the final result like such:
//
// SELECT id FROM dashboard LEFT OUTER JOIN <FilterLeftJoin...>
// WHERE <FilterWhere[0]> AND ... AND <FilterWhere[n]>
// GROUP BY <FilterGroupBy...>
// ORDER BY <FilterOrderBy...>
// LIMIT <limit> OFFSET <(page-1)*limit>;
// SELECT id FROM dashboard LEFT OUTER JOIN <FilterLeftJoin...>
// WHERE <FilterWhere[0]> AND ... AND <FilterWhere[n]>
// GROUP BY <FilterGroupBy...>
// ORDER BY <FilterOrderBy...>
// LIMIT <limit> OFFSET <(page-1)*limit>;
//
// This structure is intended to isolate the filters from each other
// and implementors are expected to add all the required joins, where
+1 -1
View File
@@ -179,7 +179,7 @@ func (ss *SQLStore) createUser(ctx context.Context, sess *DBSession, args user.C
return usr, nil
}
// deprecated method, use only for tests
// deprecated method, use only for tests
func (ss *SQLStore) CreateUser(ctx context.Context, cmd user.CreateUserCommand) (*user.User, error) {
var user user.User
createErr := ss.WithTransactionalDbSession(ctx, func(sess *DBSession) (err error) {
+1
View File
@@ -58,6 +58,7 @@ type EventHandler func(ctx context.Context, e *EntityEvent) error
// EntityEventsService is a temporary solution to support change notifications in an HA setup
// With this service each system can query for any events that have happened since a fixed time
//
//go:generate mockery --name EntityEventsService --structname MockEntityEventsService --inpackage --filename entity_events_mock.go
type EntityEventsService interface {
registry.BackgroundService
+4 -3
View File
@@ -23,9 +23,10 @@ type rootStorageSQL struct {
// getDbRootFolder creates a DB path prefix for a given storage name and orgId.
// example:
// orgId: 5
// storageName: "upload"
// => prefix: "/5/upload/"
//
// orgId: 5
// storageName: "upload"
// => prefix: "/5/upload/"
func getDbStoragePathPrefix(orgId int64, storageName string) string {
return filestorage.Join(fmt.Sprintf("%d", orgId), storageName+filestorage.Delimiter)
}
+14 -14
View File
@@ -248,7 +248,7 @@ func (s *Service) GetByID(ctx context.Context, query *user.GetUserByIDQuery) (*u
return user, nil
}
// TODO: remove wrapper around sqlstore
// TODO: remove wrapper around sqlstore
func (s *Service) GetByLogin(ctx context.Context, query *user.GetUserByLoginQuery) (*user.User, error) {
q := models.GetUserByLoginQuery{LoginOrEmail: query.LoginOrEmail}
err := s.sqlStore.GetUserByLogin(ctx, &q)
@@ -258,7 +258,7 @@ func (s *Service) GetByLogin(ctx context.Context, query *user.GetUserByLoginQuer
return q.Result, nil
}
// TODO: remove wrapper around sqlstore
// TODO: remove wrapper around sqlstore
func (s *Service) GetByEmail(ctx context.Context, query *user.GetUserByEmailQuery) (*user.User, error) {
q := models.GetUserByEmailQuery{Email: query.Email}
err := s.sqlStore.GetUserByEmail(ctx, &q)
@@ -268,7 +268,7 @@ func (s *Service) GetByEmail(ctx context.Context, query *user.GetUserByEmailQuer
return q.Result, nil
}
// TODO: remove wrapper around sqlstore
// TODO: remove wrapper around sqlstore
func (s *Service) Update(ctx context.Context, cmd *user.UpdateUserCommand) error {
q := &models.UpdateUserCommand{
Name: cmd.Name,
@@ -280,7 +280,7 @@ func (s *Service) Update(ctx context.Context, cmd *user.UpdateUserCommand) error
return s.sqlStore.UpdateUser(ctx, q)
}
// TODO: remove wrapper around sqlstore
// TODO: remove wrapper around sqlstore
func (s *Service) ChangePassword(ctx context.Context, cmd *user.ChangeUserPasswordCommand) error {
q := &models.ChangeUserPasswordCommand{
UserId: cmd.UserID,
@@ -290,7 +290,7 @@ func (s *Service) ChangePassword(ctx context.Context, cmd *user.ChangeUserPasswo
return s.sqlStore.ChangeUserPassword(ctx, q)
}
// TODO: remove wrapper around sqlstore
// TODO: remove wrapper around sqlstore
func (s *Service) UpdateLastSeenAt(ctx context.Context, cmd *user.UpdateUserLastSeenAtCommand) error {
q := &models.UpdateUserLastSeenAtCommand{
UserId: cmd.UserID,
@@ -298,7 +298,7 @@ func (s *Service) UpdateLastSeenAt(ctx context.Context, cmd *user.UpdateUserLast
return s.sqlStore.UpdateUserLastSeenAt(ctx, q)
}
// TODO: remove wrapper around sqlstore
// TODO: remove wrapper around sqlstore
func (s *Service) SetUsingOrg(ctx context.Context, cmd *user.SetUsingOrgCommand) error {
q := &models.SetUsingOrgCommand{
UserId: cmd.UserID,
@@ -307,7 +307,7 @@ func (s *Service) SetUsingOrg(ctx context.Context, cmd *user.SetUsingOrgCommand)
return s.sqlStore.SetUsingOrg(ctx, q)
}
// TODO: remove wrapper around sqlstore
// TODO: remove wrapper around sqlstore
func (s *Service) GetSignedInUserWithCacheCtx(ctx context.Context, query *user.GetSignedInUserQuery) (*user.SignedInUser, error) {
q := &models.GetSignedInUserQuery{
UserId: query.UserID,
@@ -322,7 +322,7 @@ func (s *Service) GetSignedInUserWithCacheCtx(ctx context.Context, query *user.G
return q.Result, nil
}
// TODO: remove wrapper around sqlstore
// TODO: remove wrapper around sqlstore
func (s *Service) GetSignedInUser(ctx context.Context, query *user.GetSignedInUserQuery) (*user.SignedInUser, error) {
q := &models.GetSignedInUserQuery{
UserId: query.UserID,
@@ -337,7 +337,7 @@ func (s *Service) GetSignedInUser(ctx context.Context, query *user.GetSignedInUs
return q.Result, nil
}
// TODO: remove wrapper around sqlstore
// TODO: remove wrapper around sqlstore
func (s *Service) Search(ctx context.Context, query *user.SearchUsersQuery) (*user.SearchUserQueryResult, error) {
var usrSeschHitDTOs []*user.UserSearchHitDTO
q := &models.SearchUsersQuery{
@@ -379,7 +379,7 @@ func (s *Service) Search(ctx context.Context, query *user.SearchUsersQuery) (*us
return res, nil
}
// TODO: remove wrapper around sqlstore
// TODO: remove wrapper around sqlstore
func (s *Service) Disable(ctx context.Context, cmd *user.DisableUserCommand) error {
q := &models.DisableUserCommand{
UserId: cmd.UserID,
@@ -388,7 +388,7 @@ func (s *Service) Disable(ctx context.Context, cmd *user.DisableUserCommand) err
return s.sqlStore.DisableUser(ctx, q)
}
// TODO: remove wrapper around sqlstore
// TODO: remove wrapper around sqlstore
func (s *Service) BatchDisableUsers(ctx context.Context, cmd *user.BatchDisableUsersCommand) error {
c := &models.BatchDisableUsersCommand{
UserIds: cmd.UserIDs,
@@ -397,12 +397,12 @@ func (s *Service) BatchDisableUsers(ctx context.Context, cmd *user.BatchDisableU
return s.sqlStore.BatchDisableUsers(ctx, c)
}
// TODO: remove wrapper around sqlstore
// TODO: remove wrapper around sqlstore
func (s *Service) UpdatePermissions(userID int64, isAdmin bool) error {
return s.sqlStore.UpdateUserPermissions(userID, isAdmin)
}
// TODO: remove wrapper around sqlstore
// TODO: remove wrapper around sqlstore
func (s *Service) SetUserHelpFlag(ctx context.Context, cmd *user.SetUserHelpFlagCommand) error {
c := &models.SetUserHelpFlagCommand{
UserId: cmd.UserID,
@@ -411,7 +411,7 @@ func (s *Service) SetUserHelpFlag(ctx context.Context, cmd *user.SetUserHelpFlag
return s.sqlStore.SetUserHelpFlag(ctx, c)
}
// TODO: remove wrapper around sqlstore
// TODO: remove wrapper around sqlstore
func (s *Service) GetUserProfile(ctx context.Context, query *user.GetUserProfileQuery) (user.UserProfileDTO, error) {
q := &models.GetUserProfileQuery{
UserId: query.UserID,
@@ -913,6 +913,9 @@ func newMockNotificationChannel(t *testing.T, grafanaListedAddr string) *mockNot
require.NoError(t, err)
nc := &mockNotificationChannel{
// Skip gosec linter since this is in test code.
//
//nolint:gosec
server: &http.Server{
Addr: listener.Addr().String(),
},
@@ -12,8 +12,9 @@ import (
"github.com/grafana/grafana-plugin-sdk-go/backend"
"github.com/grafana/grafana-plugin-sdk-go/data"
"github.com/grafana/grafana/pkg/infra/tracing"
"go.opentelemetry.io/otel/attribute"
"github.com/grafana/grafana/pkg/infra/tracing"
)
func (timeSeriesFilter *cloudMonitoringTimeSeriesFilter) run(ctx context.Context, req *backend.QueryDataRequest,
@@ -82,7 +83,7 @@ func (timeSeriesFilter *cloudMonitoringTimeSeriesFilter) run(ctx context.Context
return dr, d, r.URL.RawQuery, nil
}
//nolint: gocyclo
//nolint:gocyclo
func (timeSeriesFilter *cloudMonitoringTimeSeriesFilter) parseResponse(queryRes *backend.DataResponse,
response cloudMonitoringResponse, executedQueryString string) error {
frames := data.Frames{}
+12 -12
View File
@@ -29,18 +29,18 @@ const (
//
// we also try to detect some often used patterns in the data,
// and make the data easier to graph in the browser for such cases:
// - if there is only one timestamp-column and it's named "_time",
// we will not add the labels to this data-column, because timestamp
// columns usually do not have labels in grafana.
// we use the `columnInfo.shouldGetLabels` attribute to handle this.
// - if there is only one timestamp-column and it's named "_time",
// and there is only one non-timestamp-column and it's named "_value",
// we rename "_time" to "Time" (using `columnInfo.isTheSimpleTime`),
// and we rename "_value" too (using `columnInfo.isTheSimpleValue`):
// if there is a tag called "_field" we use it's value as the name
// (because that's the usual approach in influxdb), and if there is not,
// we name it "Value". with these new names, they are more compatible
// with the visualizations in grafana.
// - if there is only one timestamp-column and it's named "_time",
// we will not add the labels to this data-column, because timestamp
// columns usually do not have labels in grafana.
// we use the `columnInfo.shouldGetLabels` attribute to handle this.
// - if there is only one timestamp-column and it's named "_time",
// and there is only one non-timestamp-column and it's named "_value",
// we rename "_time" to "Time" (using `columnInfo.isTheSimpleTime`),
// and we rename "_value" too (using `columnInfo.isTheSimpleValue`):
// if there is a tag called "_field" we use it's value as the name
// (because that's the usual approach in influxdb), and if there is not,
// we name it "Value". with these new names, they are more compatible
// with the visualizations in grafana.
type columnInfo struct {
name string
converter *data.FieldConverter
+1 -1
View File
@@ -156,7 +156,7 @@ func FormatDuration(inter time.Duration) string {
return "1ms"
}
//nolint: gocyclo
//nolint:gocyclo
func roundInterval(interval time.Duration) time.Duration {
switch {
// 0.01s
+1 -1
View File
@@ -146,7 +146,7 @@ func FormatDuration(inter time.Duration) string {
return "1ms"
}
//nolint: gocyclo
//nolint:gocyclo
func roundInterval(interval time.Duration) time.Duration {
switch {
// 0.015s
+1 -1
View File
@@ -33,7 +33,7 @@ func ProvideService(pluginsClient plugins.Client, oAuthTokenService oauthtoken.O
}
}
//nolint: staticcheck // legacydata.DataResponse deprecated
//nolint:staticcheck // legacydata.DataResponse deprecated
func (h *Service) HandleRequest(ctx context.Context, ds *datasources.DataSource, query legacydata.DataQuery) (legacydata.DataResponse, error) {
decryptedJsonData, err := h.dataSourcesService.DecryptedValues(ctx, ds)
if err != nil {
+1 -1
View File
@@ -189,7 +189,7 @@ func formatNamePrometheusStyle(labels map[string]string) string {
return fmt.Sprintf("{%s}", strings.Join(parts, ", "))
}
//If legend (using of name or pattern instead of time series name) is used, use that name/pattern for formatting
// If legend (using of name or pattern instead of time series name) is used, use that name/pattern for formatting
func formatName(labels map[string]string, query *lokiQuery) string {
if query.LegendFormat == "" {
return formatNamePrometheusStyle(labels)
+1
View File
@@ -57,6 +57,7 @@ func TestSuccessResponse(t *testing.T) {
responseFileName := filepath.Join("testdata", test.filepath+".json")
goldenFileName := test.filepath + ".golden"
//nolint:gosec
bytes, err := os.ReadFile(responseFileName)
require.NoError(t, err)
+2 -1
View File
@@ -8,6 +8,7 @@ import (
"github.com/grafana/grafana-plugin-sdk-go/backend"
"github.com/grafana/grafana-plugin-sdk-go/backend/gtime"
"github.com/grafana/grafana/pkg/tsdb/sqleng"
)
@@ -65,7 +66,7 @@ func (m *postgresMacroEngine) Interpolate(query *backend.DataQuery, timeRange ba
return sql, nil
}
//nolint: gocyclo
//nolint:gocyclo
func (m *postgresMacroEngine) evaluateMacro(timeRange backend.TimeRange, query *backend.DataQuery, name string, args []string) (string, error) {
switch name {
case "__time":
+5 -2
View File
@@ -15,11 +15,12 @@ import (
"github.com/grafana/grafana-plugin-sdk-go/backend"
"github.com/grafana/grafana-plugin-sdk-go/experimental"
"github.com/prometheus/client_golang/api"
apiv1 "github.com/prometheus/client_golang/api/prometheus/v1"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/infra/tracing"
"github.com/grafana/grafana/pkg/tsdb/intervalv2"
"github.com/prometheus/client_golang/api"
apiv1 "github.com/prometheus/client_golang/api/prometheus/v1"
)
var update = true
@@ -44,6 +45,7 @@ func TestMatrixResponses(t *testing.T) {
query, err := loadStoredPrometheusQuery(queryFileName)
require.NoError(t, err)
//nolint:gosec
responseBytes, err := os.ReadFile(responseFileName)
require.NoError(t, err)
@@ -101,6 +103,7 @@ type storedPrometheusQuery struct {
}
func loadStoredPrometheusQuery(fileName string) (PrometheusQuery, error) {
//nolint:gosec
bytes, err := os.ReadFile(fileName)
if err != nil {
return PrometheusQuery{}, err
@@ -24,7 +24,7 @@ import (
"go.opentelemetry.io/otel/attribute"
)
//Internal interval and range variables
// Internal interval and range variables
const (
varInterval = "$__interval"
varIntervalMs = "$__interval_ms"
@@ -34,8 +34,8 @@ const (
varRateInterval = "$__rate_interval"
)
//Internal interval and range variables with {} syntax
//Repetitive code, we should have functionality to unify these
// Internal interval and range variables with {} syntax
// Repetitive code, we should have functionality to unify these
const (
varIntervalAlt = "${__interval}"
varIntervalMsAlt = "${__interval_ms}"
+3 -3
View File
@@ -11,7 +11,7 @@ import (
"github.com/grafana/grafana/pkg/tsdb/intervalv2"
)
//Internal interval and range variables
// Internal interval and range variables
const (
varInterval = "$__interval"
varIntervalMs = "$__interval_ms"
@@ -21,8 +21,8 @@ const (
varRateInterval = "$__rate_interval"
)
//Internal interval and range variables with {} syntax
//Repetitive code, we should have functionality to unify these
// Internal interval and range variables with {} syntax
// Repetitive code, we should have functionality to unify these
const (
varIntervalAlt = "${__interval}"
varIntervalMsAlt = "${__interval_ms}"
@@ -16,6 +16,7 @@ import (
"github.com/grafana/grafana-plugin-sdk-go/backend"
"github.com/grafana/grafana-plugin-sdk-go/experimental"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/tsdb/prometheus/models"
)
@@ -50,6 +51,7 @@ func goldenScenario(name, queryFileName, responseFileName, goldenFileName string
query, err := loadStoredQuery(queryFileName)
require.NoError(t, err)
//nolint:gosec
responseBytes, err := os.ReadFile(responseFileName)
require.NoError(t, err)
@@ -78,6 +80,7 @@ type storedPrometheusQuery struct {
}
func loadStoredQuery(fileName string) (*backend.QueryDataRequest, error) {
//nolint:gosec
bytes, err := os.ReadFile(fileName)
if err != nil {
return nil, err
+6 -3
View File
@@ -16,10 +16,11 @@ import (
"github.com/grafana/grafana-plugin-sdk-go/backend"
"github.com/grafana/grafana-plugin-sdk-go/data"
"github.com/grafana/grafana-plugin-sdk-go/data/sqlutil"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/tsdb/intervalv2"
"xorm.io/core"
"xorm.io/xorm"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/tsdb/intervalv2"
)
// MetaKeyExecutedQueryString is the key where the executed query should get stored
@@ -43,6 +44,7 @@ type SqlQueryResultTransformer interface {
var sqlIntervalCalculator = intervalv2.NewCalculator()
// NewXormEngine is an xorm.Engine factory, that can be stubbed by tests.
//
//nolint:gocritic
var NewXormEngine = func(driverName string, connectionString string) (*xorm.Engine, error) {
return xorm.NewEngine(driverName, connectionString)
@@ -886,7 +888,8 @@ func convertSQLTimeColumnToEpochMS(frame *data.Frame, timeIndex int) error {
}
// convertSQLValueColumnToFloat converts timeseries value column to float.
//nolint: gocyclo
//
//nolint:gocyclo
func convertSQLValueColumnToFloat(frame *data.Frame, Index int) (*data.Frame, error) {
if Index < 0 || Index >= len(frame.Fields) {
return frame, fmt.Errorf("metricIndex %d is out of range", Index)
+6 -4
View File
@@ -115,8 +115,9 @@ func describeReflectValue(v reflect.Value) interface{} {
}
// IsAddOperation returns true when
// - Left does not have value and Right has
// - the kind of Left and Right is either reflect.Slice or reflect.Map and the length of Left is less than length of Right
// - Left does not have value and Right has
// - the kind of Left and Right is either reflect.Slice or reflect.Map and the length of Left is less than length of Right
//
// In all other cases it returns false.
// NOTE: this is applicable to diff of Maps and Slices only
func (d *Diff) IsAddOperation() bool {
@@ -125,8 +126,9 @@ func (d *Diff) IsAddOperation() bool {
}
// IsDeleteOperation returns true when
// - Right does not have value and Left has
// - the kind of Left and Right is either reflect.Slice or reflect.Map and the length of Right is less than length of Left
// - Right does not have value and Left has
// - the kind of Left and Right is either reflect.Slice or reflect.Map and the length of Right is less than length of Left
//
// In all other cases it returns false.
// NOTE: this is applicable to diff of Maps and Slices only
func (d *Diff) IsDeleteOperation() bool {
+1
View File
@@ -45,6 +45,7 @@ func TestReadPromFrames(t *testing.T) {
}
// FIXME:
//
//lint:ignore U1000 Ignore used function for now
func runScenario(name string, opts Options) func(t *testing.T) {
return func(t *testing.T) {
+8 -3
View File
@@ -26,16 +26,21 @@
// service using the NewBase constructor with a CoreStatus and a unique
// static message ID that identifies the general structure of the public
// message attached to the specific error.
// var errNotFound = errutil.NewBase(errutil.StatusNotFound, "service.not-found")
//
// var errNotFound = errutil.NewBase(errutil.StatusNotFound, "service.not-found")
//
// This Base can now be used to construct a regular Go error with the
// Base.Errorf method using the same structure as fmt.Errorf:
// return errNotFound.Errorf("looked for thing with ID %d, but it wasn't there: %w", id, err)
//
// return errNotFound.Errorf("looked for thing with ID %d, but it wasn't there: %w", id, err)
//
// By default, the end user will be sent the static message ID and a
// message which is the string representation of the CoreStatus. It is
// possible to override the message sent to the end user by using
// the WithPublicMessage functional option when creating a new Base
// var errNotFound = errutil.NewBase(errutil.StatusNotFound "service.not-found", WithPublicMessage("The thing is missing."))
//
// var errNotFound = errutil.NewBase(errutil.StatusNotFound "service.not-found", WithPublicMessage("The thing is missing."))
//
// If a dynamic message is needed, the Template type extends Base with a
// Go template using text/template from the standard library, refer to
// the documentation related to the Template type for usage examples.
+4 -3
View File
@@ -23,9 +23,10 @@ type Base struct {
// to serve as the base for user facing error messages.
//
// msgID should be structured as component.error-brief, for example
// login.failed-authentication
// dashboards.validation-error
// dashboards.uid-already-exists
//
// login.failed-authentication
// dashboards.validation-error
// dashboards.uid-already-exists
func NewBase(reason StatusReason, msgID string, opts ...BaseOpt) Base {
b := Base{
reason: reason,