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
pull/55026/head
Emil Tullstedt 3 years ago committed by GitHub
parent 5388dc6a2f
commit b287047052
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 6
      .bingo/Variables.mk
  2. 173
      .bingo/golangci-lint.mod
  3. 930
      .bingo/golangci-lint.sum
  4. 2
      .bingo/variables.env
  5. 416
      .drone.yml
  6. 12
      .golangci.toml
  7. 2
      Dockerfile
  8. 2
      Dockerfile.ubuntu
  9. 2
      Makefile
  10. 1
      pkg/build/plugins/download.go
  11. 1
      pkg/build/plugins/manifest.go
  12. 4
      pkg/cmd/grafana-server/commands/cli.go
  13. 13
      pkg/components/loki/logproto/logproto.pb.go
  14. 4
      pkg/components/loki/logproto/types.go
  15. 61
      pkg/components/simplejson/simplejson.go
  16. 2
      pkg/coremodel/dashboard/dashboards_test.go
  17. 2
      pkg/expr/classic/reduce.go
  18. 1
      pkg/ifaces/gcsifaces/gcsifaces.go
  19. 5
      pkg/infra/filestorage/cdk_blob_filestorage.go
  20. 2
      pkg/infra/filestorage/db_filestorage.go
  21. 1
      pkg/infra/fs/copy.go
  22. 2
      pkg/infra/log/databaseCounter.go
  23. 5
      pkg/infra/log/term/terminal_logger.go
  24. 3
      pkg/infra/remotecache/remotecache.go
  25. 2
      pkg/models/dashboard_acl.go
  26. 5
      pkg/plugins/backendplugin/pluginextensionv2/rendererv2.pb.go
  27. 5
      pkg/plugins/backendplugin/pluginextensionv2/sanitizer.pb.go
  28. 5
      pkg/plugins/backendplugin/secretsmanagerplugin/secretsmanager.pb.go
  29. 1
      pkg/plugins/backendplugin/secretsmanagerplugin/secretsmanager_grpc.pb.go
  30. 2
      pkg/plugins/storage/fs_test.go
  31. 4
      pkg/services/alerting/conditions/query_interval_test.go
  32. 4
      pkg/services/alerting/conditions/query_test.go
  33. 2
      pkg/services/alerting/conditions/reducer.go
  34. 3
      pkg/services/alerting/notifier.go
  35. 3
      pkg/services/alerting/notifiers/googlechat.go
  36. 8
      pkg/services/alerting/ticker.go
  37. 11
      pkg/services/auth/jwt/validation.go
  38. 12
      pkg/services/dashboards/dashboard.go
  39. 3
      pkg/services/dashboards/folder.go
  40. 3
      pkg/services/featuremgmt/strcase/snake.go
  41. 25
      pkg/services/ngalert/api/tooling/definitions/api.go
  42. 33
      pkg/services/ngalert/eval/eval.go
  43. 10
      pkg/services/ngalert/eval/evaluator_mock.go
  44. 11
      pkg/services/ngalert/notifier/channels/testing.go
  45. 1
      pkg/services/ngalert/notifier/channels/util.go
  46. 3
      pkg/services/ngalert/provisioning/persist.go
  47. 8
      pkg/services/ngalert/provisioning/persist_mock.go
  48. 26
      pkg/services/ngalert/provisioning/provisioning_store_mock.go
  49. 6
      pkg/services/ngalert/provisioning/quota_checker_mock.go
  50. 4
      pkg/services/ngalert/schedule/alerts_sender_mock.go
  51. 2
      pkg/services/ngalert/schedule/schedule_test.go
  52. 6
      pkg/services/ngalert/store/admin_configuration_store_mock.go
  53. 2
      pkg/services/org/orgimpl/org.go
  54. 9
      pkg/services/provisioning/values/values.go
  55. 2
      pkg/services/publicdashboards/api/api.go
  56. 2
      pkg/services/publicdashboards/api/api_test.go
  57. 2
      pkg/services/publicdashboards/models/models.go
  58. 1
      pkg/services/rendering/http_mode.go
  59. 1
      pkg/services/screenshot/screenshot.go
  60. 3
      pkg/services/searchV2/bluge.go
  61. 4
      pkg/services/searchV2/extract/dashboard_test.go
  62. 1
      pkg/services/sqlstore/migrations/ualert/silences.go
  63. 2
      pkg/services/sqlstore/migrations/ualert/ualert.go
  64. 2
      pkg/services/sqlstore/migrator/dialect.go
  65. 4
      pkg/services/sqlstore/org_test.go
  66. 10
      pkg/services/sqlstore/searchstore/doc.go
  67. 2
      pkg/services/sqlstore/user.go
  68. 1
      pkg/services/store/entity_events.go
  69. 7
      pkg/services/store/storage_sql.go
  70. 28
      pkg/services/user/userimpl/user.go
  71. 3
      pkg/tests/api/alerting/api_notification_channel_test.go
  72. 5
      pkg/tsdb/cloudmonitoring/time_series_filter.go
  73. 24
      pkg/tsdb/influxdb/flux/builder.go
  74. 2
      pkg/tsdb/intervalv2/intervalv2.go
  75. 2
      pkg/tsdb/legacydata/interval/interval.go
  76. 2
      pkg/tsdb/legacydata/service/service.go
  77. 2
      pkg/tsdb/loki/frame.go
  78. 1
      pkg/tsdb/loki/framing_test.go
  79. 3
      pkg/tsdb/postgres/macros.go
  80. 7
      pkg/tsdb/prometheus/buffered/framing_test.go
  81. 6
      pkg/tsdb/prometheus/buffered/time_series_query.go
  82. 6
      pkg/tsdb/prometheus/models/query.go
  83. 3
      pkg/tsdb/prometheus/querydata/framing_test.go
  84. 9
      pkg/tsdb/sqleng/sql_engine.go
  85. 10
      pkg/util/cmputil/reporter.go
  86. 1
      pkg/util/converter/prom_test.go
  87. 11
      pkg/util/errutil/doc.go
  88. 7
      pkg/util/errutil/errors.go
  89. 19
      scripts/build/ci-build/Dockerfile
  90. 2
      scripts/build/ci-build/README.md
  91. 5
      scripts/drone/steps/lib.star

@ -35,11 +35,11 @@ $(SWAGGER): $(BINGO_DIR)/swagger.mod
@echo "(re)installing $(GOBIN)/swagger-v0.29.0"
@cd $(BINGO_DIR) && $(GO) build -mod=mod -modfile=swagger.mod -o=$(GOBIN)/swagger-v0.29.0 "github.com/go-swagger/go-swagger/cmd/swagger"
GOLANGCI_LINT := $(GOBIN)/golangci-lint-v1.40.1
GOLANGCI_LINT := $(GOBIN)/golangci-lint-v1.49.0
$(GOLANGCI_LINT): $(BINGO_DIR)/golangci-lint.mod
@# Install binary/ries using Go 1.14+ build command. This is using bwplotka/bingo-controlled, separate go module with pinned dependencies.
@echo "(re)installing $(GOBIN)/golangci-lint-v1.40.1"
@cd $(BINGO_DIR) && $(GO) build -mod=mod -modfile=golangci-lint.mod -o=$(GOBIN)/golangci-lint-v1.40.1 "github.com/golangci/golangci-lint/cmd/golangci-lint"
@echo "(re)installing $(GOBIN)/golangci-lint-v1.49.0"
@cd $(BINGO_DIR) && $(GO) build -mod=mod -modfile=golangci-lint.mod -o=$(GOBIN)/golangci-lint-v1.49.0 "github.com/golangci/golangci-lint/cmd/golangci-lint"
WIRE := $(GOBIN)/wire-v0.5.0
$(WIRE): $(BINGO_DIR)/wire.mod

@ -1,5 +1,174 @@
module _ // Auto generated by https://github.com/bwplotka/bingo. DO NOT EDIT
go 1.17
go 1.19
require github.com/golangci/golangci-lint v1.40.1 // cmd/golangci-lint
require github.com/golangci/golangci-lint v1.49.0 // cmd/golangci-lint
require (
4d63.com/gochecknoglobals v0.1.0 // indirect
github.com/Antonboom/errname v0.1.7 // indirect
github.com/Antonboom/nilnil v0.1.1 // indirect
github.com/BurntSushi/toml v1.2.0 // indirect
github.com/Djarvur/go-err113 v0.0.0-20210108212216-aea10b59be24 // indirect
github.com/GaijinEntertainment/go-exhaustruct/v2 v2.3.0 // indirect
github.com/Masterminds/semver v1.5.0 // indirect
github.com/OpenPeeDeeP/depguard v1.1.0 // indirect
github.com/alexkohler/prealloc v1.0.0 // indirect
github.com/alingse/asasalint v0.0.11 // indirect
github.com/ashanbrown/forbidigo v1.3.0 // indirect
github.com/ashanbrown/makezero v1.1.1 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/bkielbasa/cyclop v1.2.0 // indirect
github.com/blizzy78/varnamelen v0.8.0 // indirect
github.com/bombsimon/wsl/v3 v3.3.0 // indirect
github.com/breml/bidichk v0.2.3 // indirect
github.com/breml/errchkjson v0.3.0 // indirect
github.com/butuzov/ireturn v0.1.1 // indirect
github.com/cespare/xxhash/v2 v2.1.2 // indirect
github.com/charithe/durationcheck v0.0.9 // indirect
github.com/chavacava/garif v0.0.0-20220630083739-93517212f375 // indirect
github.com/curioswitch/go-reassign v0.1.2 // indirect
github.com/daixiang0/gci v0.6.3 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/denis-tingaikin/go-header v0.4.3 // indirect
github.com/esimonov/ifshort v1.0.4 // indirect
github.com/ettle/strcase v0.1.1 // indirect
github.com/fatih/color v1.13.0 // indirect
github.com/fatih/structtag v1.2.0 // indirect
github.com/firefart/nonamedreturns v1.0.4 // indirect
github.com/fsnotify/fsnotify v1.5.4 // indirect
github.com/fzipp/gocyclo v0.6.0 // indirect
github.com/go-critic/go-critic v0.6.4 // indirect
github.com/go-toolsmith/astcast v1.0.0 // indirect
github.com/go-toolsmith/astcopy v1.0.1 // indirect
github.com/go-toolsmith/astequal v1.0.2 // indirect
github.com/go-toolsmith/astfmt v1.0.0 // indirect
github.com/go-toolsmith/astp v1.0.0 // indirect
github.com/go-toolsmith/strparse v1.0.0 // indirect
github.com/go-toolsmith/typep v1.0.2 // indirect
github.com/go-xmlfmt/xmlfmt v0.0.0-20191208150333-d5b6f63a941b // indirect
github.com/gobwas/glob v0.2.3 // indirect
github.com/gofrs/flock v0.8.1 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/golangci/check v0.0.0-20180506172741-cfe4005ccda2 // indirect
github.com/golangci/dupl v0.0.0-20180902072040-3e9179ac440a // indirect
github.com/golangci/go-misc v0.0.0-20220329215616-d24fe342adfe // indirect
github.com/golangci/gofmt v0.0.0-20190930125516-244bba706f1a // indirect
github.com/golangci/lint-1 v0.0.0-20191013205115-297bf364a8e0 // indirect
github.com/golangci/maligned v0.0.0-20180506175553-b1d89398deca // indirect
github.com/golangci/misspell v0.3.5 // indirect
github.com/golangci/revgrep v0.0.0-20220804021717-745bb2f7c2e6 // indirect
github.com/golangci/unconvert v0.0.0-20180507085042-28b1c447d1f4 // indirect
github.com/google/go-cmp v0.5.8 // indirect
github.com/gordonklaus/ineffassign v0.0.0-20210914165742-4cc7213b9bc8 // indirect
github.com/gostaticanalysis/analysisutil v0.7.1 // indirect
github.com/gostaticanalysis/comment v1.4.2 // indirect
github.com/gostaticanalysis/forcetypeassert v0.1.0 // indirect
github.com/gostaticanalysis/nilerr v0.1.1 // indirect
github.com/hashicorp/errwrap v1.0.0 // indirect
github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/hashicorp/go-version v1.6.0 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/hexops/gotextdiff v1.0.3 // indirect
github.com/inconshreveable/mousetrap v1.0.0 // indirect
github.com/jgautheron/goconst v1.5.1 // indirect
github.com/jingyugao/rowserrcheck v1.1.1 // indirect
github.com/jirfag/go-printf-func-name v0.0.0-20200119135958-7558a9eaa5af // indirect
github.com/julz/importas v0.1.0 // indirect
github.com/kisielk/errcheck v1.6.2 // indirect
github.com/kisielk/gotool v1.0.0 // indirect
github.com/kulti/thelper v0.6.3 // indirect
github.com/kunwardeep/paralleltest v1.0.6 // indirect
github.com/kyoh86/exportloopref v0.1.8 // indirect
github.com/ldez/gomoddirectives v0.2.3 // indirect
github.com/ldez/tagliatelle v0.3.1 // indirect
github.com/leonklingele/grouper v1.1.0 // indirect
github.com/lufeee/execinquery v1.2.1 // indirect
github.com/magiconair/properties v1.8.6 // indirect
github.com/maratori/testpackage v1.1.0 // indirect
github.com/matoous/godox v0.0.0-20210227103229-6504466cf951 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.16 // indirect
github.com/mattn/go-runewidth v0.0.9 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
github.com/mbilski/exhaustivestruct v1.2.0 // indirect
github.com/mgechev/revive v1.2.3 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/moricho/tparallel v0.2.1 // indirect
github.com/nakabonne/nestif v0.3.1 // indirect
github.com/nbutton23/zxcvbn-go v0.0.0-20210217022336-fa2cb2858354 // indirect
github.com/nishanths/exhaustive v0.8.1 // indirect
github.com/nishanths/predeclared v0.2.2 // indirect
github.com/olekukonko/tablewriter v0.0.5 // indirect
github.com/pelletier/go-toml v1.9.5 // indirect
github.com/pelletier/go-toml/v2 v2.0.2 // indirect
github.com/phayes/checkstyle v0.0.0-20170904204023-bfd46e6a821d // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/polyfloyd/go-errorlint v1.0.2 // indirect
github.com/prometheus/client_golang v1.12.1 // indirect
github.com/prometheus/client_model v0.2.0 // indirect
github.com/prometheus/common v0.32.1 // indirect
github.com/prometheus/procfs v0.7.3 // indirect
github.com/quasilyte/go-ruleguard v0.3.17 // indirect
github.com/quasilyte/gogrep v0.0.0-20220120141003-628d8b3623b5 // indirect
github.com/quasilyte/regex/syntax v0.0.0-20200407221936-30656e2c4a95 // indirect
github.com/quasilyte/stdinfo v0.0.0-20220114132959-f7386bf02567 // indirect
github.com/ryancurrah/gomodguard v1.2.4 // indirect
github.com/ryanrolds/sqlclosecheck v0.3.0 // indirect
github.com/sanposhiho/wastedassign/v2 v2.0.6 // indirect
github.com/sashamelentyev/interfacebloat v1.1.0 // indirect
github.com/sashamelentyev/usestdlibvars v1.13.0 // indirect
github.com/securego/gosec/v2 v2.13.1 // indirect
github.com/shazow/go-diff v0.0.0-20160112020656-b6b7b6733b8c // indirect
github.com/sirupsen/logrus v1.9.0 // indirect
github.com/sivchari/containedctx v1.0.2 // indirect
github.com/sivchari/nosnakecase v1.7.0 // indirect
github.com/sivchari/tenv v1.7.0 // indirect
github.com/sonatard/noctx v0.0.1 // indirect
github.com/sourcegraph/go-diff v0.6.1 // indirect
github.com/spf13/afero v1.8.2 // indirect
github.com/spf13/cast v1.5.0 // indirect
github.com/spf13/cobra v1.5.0 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/spf13/viper v1.12.0 // indirect
github.com/ssgreg/nlreturn/v2 v2.2.1 // indirect
github.com/stbenjam/no-sprintf-host-port v0.1.1 // indirect
github.com/stretchr/objx v0.4.0 // indirect
github.com/stretchr/testify v1.8.0 // indirect
github.com/subosito/gotenv v1.4.0 // indirect
github.com/sylvia7788/contextcheck v1.0.6 // indirect
github.com/tdakkota/asciicheck v0.1.1 // indirect
github.com/tetafro/godot v1.4.11 // indirect
github.com/timakin/bodyclose v0.0.0-20210704033933-f49887972144 // indirect
github.com/timonwong/logrlint v0.1.0 // indirect
github.com/tomarrell/wrapcheck/v2 v2.6.2 // indirect
github.com/tommy-muehle/go-mnd/v2 v2.5.0 // indirect
github.com/ultraware/funlen v0.0.3 // indirect
github.com/ultraware/whitespace v0.0.5 // indirect
github.com/uudashr/gocognit v1.0.6 // indirect
github.com/yagipy/maintidx v1.0.0 // indirect
github.com/yeya24/promlinter v0.2.0 // indirect
gitlab.com/bosi/decorder v0.2.3 // indirect
go.uber.org/atomic v1.7.0 // indirect
go.uber.org/multierr v1.6.0 // indirect
go.uber.org/zap v1.17.0 // indirect
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e // indirect
golang.org/x/exp/typeparams v0.0.0-20220613132600-b0d781184e0d // indirect
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 // indirect
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4 // indirect
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab // indirect
golang.org/x/text v0.3.7 // indirect
golang.org/x/tools v0.1.12 // indirect
google.golang.org/protobuf v1.28.0 // indirect
gopkg.in/ini.v1 v1.66.6 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
honnef.co/go/tools v0.3.3 // indirect
mvdan.cc/gofumpt v0.3.1 // indirect
mvdan.cc/interfacer v0.0.0-20180901003855-c20040233aed // indirect
mvdan.cc/lint v0.0.0-20170908181259-adc824a0674b // indirect
mvdan.cc/unparam v0.0.0-20220706161116-678bad134442 // indirect
)

File diff suppressed because it is too large Load Diff

@ -14,7 +14,7 @@ DRONE="${GOBIN}/drone-v1.5.0"
SWAGGER="${GOBIN}/swagger-v0.29.0"
GOLANGCI_LINT="${GOBIN}/golangci-lint-v1.40.1"
GOLANGCI_LINT="${GOBIN}/golangci-lint-v1.49.0"
WIRE="${GOBIN}/wire-v0.5.0"

File diff suppressed because it is too large Load Diff

@ -29,13 +29,12 @@ rules = "pkg/ruleguard.rules.go"
disable-all = true
enable = [
"bodyclose",
"deadcode",
"depguard",
"dogsled",
"errcheck",
# "gochecknoinits",
"goconst",
"gocritic",
# "gocritic", # Temporarily disabled on 2022-09-09, running into weird bug "ruleguard: execution error: used Run() with an empty rule set; forgot to call Load() first?"
"goimports",
"goprintffuncname",
"gosec",
@ -47,12 +46,10 @@ enable = [
"rowserrcheck",
"exportloopref",
"staticcheck",
"structcheck",
"stylecheck",
"typecheck",
"unconvert",
"unused",
"varcheck",
"whitespace",
"gocyclo",
"exhaustive",
@ -81,6 +78,13 @@ text = "ST1003"
linters = ["stylecheck"]
text = "ST1001"
# Enable when appropriate
# strings.Title has been deprecated since Go 1.18 and an alternative has been available since Go 1.0: The rule Title uses for word boundaries does not handle Unicode punctuation properly.
# Use golang.org/x/text/cases instead.
[[issues.exclude-rules]]
linters = ["staticcheck"]
text = "SA1019"
[[issues.exclude-rules]]
linters = ["gosec"]
text = "G108"

@ -20,7 +20,7 @@ COPY emails emails
ENV NODE_ENV production
RUN yarn build
FROM golang:1.17.12-alpine3.15 as go-builder
FROM golang:1.19.1-alpine3.15 as go-builder
RUN apk add --no-cache gcc g++ make

@ -21,7 +21,7 @@ COPY emails emails
ENV NODE_ENV production
RUN yarn build
FROM golang:1.17.12 AS go-builder
FROM golang:1.19.1 AS go-builder
WORKDIR /src/grafana

@ -134,7 +134,7 @@ test: test-go test-js ## Run all tests.
golangci-lint: $(GOLANGCI_LINT)
@echo "lint via golangci-lint"
$(GOLANGCI_LINT) run \
--config ./conf/.golangci.toml \
--config .golangci.toml \
$(GO_FILES)
lint-go: golangci-lint ## Run all code checks for backend. You can use GO_FILES to specify exact files to check

@ -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

@ -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)

@ -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)

@ -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.

@ -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

@ -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

@ -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 {

@ -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,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{

@ -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

@ -75,6 +75,7 @@ func copyFileContents(src, dst string) (err error) {
}
}()
//nolint:gosec
out, err := os.Create(dst)
if err != nil {
return

@ -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)
}

@ -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}
}

@ -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)

@ -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"

@ -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

@ -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)

@ -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
*/

@ -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,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)
}

@ -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)

@ -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)

@ -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

@ -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)

@ -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)}
}

@ -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,

@ -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 (

@ -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

@ -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

@ -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)

@ -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

@ -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 ""
}

@ -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()

@ -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

@ -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) {

@ -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

@ -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)
}

@ -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{}

@ -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

@ -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

@ -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

@ -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 {

@ -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)

@ -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)

@ -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":

@ -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}"

@ -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

@ -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)

@ -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 {

@ -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) {

@ -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.

@ -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,

@ -1,5 +1,5 @@
# Use old Debian (this has support into 2022) in order to ensure binary compatibility with older glibc's.
FROM debian:stretch-20210208 AS toolchain
# Use old Debian (LTS into 2024) in order to ensure binary compatibility with older glibc's.
FROM debian:buster-20220822 AS toolchain
ENV OSX_MIN=10.10 \
CTNG=1.24.0 \
@ -99,13 +99,13 @@ RUN tar -xzvf dockerize-linux-amd64-v${DOCKERIZE_VERSION}.tar.gz -C /tmp/
RUN rm dockerize-linux-amd64-v${DOCKERIZE_VERSION}.tar.gz
# Base image to crossbuild grafana.
# Use old Debian (this has support into 2022) in order to ensure binary compatibility with older glibc's.
FROM debian:stretch-20210208
# Use old Debian (LTS into 2024) in order to ensure binary compatibility with older glibc's.
FROM debian:buster-20220822
ENV GOVERSION=1.17.12 \
ENV GOVERSION=1.19.1 \
PATH=/usr/local/go/bin:$PATH \
GOPATH=/go \
NODEVERSION=16.14.0-1nodesource1 \
NODEVERSION=16.17.0-1nodesource1 \
YARNVERSION=1.22.19-1
# Use ARG so as not to persist environment variable in image
@ -126,7 +126,7 @@ RUN apt-get update && \
gcc \
g++ \
git \
jq \
jq \
make \
rpm \
xz-utils \
@ -136,8 +136,9 @@ RUN apt-get update && \
ruby \
ruby-dev \
rubygems \
unzip && \
gem install -N fpm && \
unzip && \
gem install -N public_suffix -v 4.0.7 && \
gem install --conservative -N fpm && \
ln -s /usr/bin/llvm-dsymutil-6.0 /usr/bin/dsymutil && \
curl -fsS https://deb.nodesource.com/gpgkey/nodesource.gpg.key | apt-key add - && \
curl -O https://deb.nodesource.com/node_16.x/pool/main/n/nodejs/nodejs_${NODEVERSION}_amd64.deb &&\

@ -3,7 +3,7 @@
These are the sources for the Docker image that we use for the Grafana build containers. The image source itself
is in Dockerfile, but there are supporting scripts such as the Makefile, for building images.
The image is based on Debian Stretch, since we want an older Linux distribution (Stretch has long-term support into 2022) to build binaries that are as portable as possible.
The image is based on Debian Buster, since we want an older Linux distribution (Buster has long-term support into 2024) to build binaries that are as portable as possible.
## Build/Publish Docker Image

@ -1,13 +1,14 @@
load('scripts/drone/vault.star', 'from_secret', 'github_token', 'pull_secret', 'drone_token', 'prerelease_bucket')
grabpl_version = 'v3.0.6'
build_image = 'grafana/build-container:1.5.9'
build_image = 'grafana/build-container:1.6.1'
publish_image = 'grafana/grafana-ci-deploy:1.3.3'
deploy_docker_image = 'us.gcr.io/kubernetes-dev/drone/plugins/deploy-image'
alpine_image = 'alpine:3.15.6'
curl_image = 'byrnedo/alpine-curl:0.1.8'
windows_image = 'mcr.microsoft.com/windows:1809'
wix_image = 'grafana/ci-wix:0.1.1'
go_image = 'golang:1.19.1'
disable_tests = False
trigger_oss = {
@ -1251,7 +1252,7 @@ def compile_build_cmd(edition='oss'):
dependencies = ['init-enterprise',]
return {
'name': 'compile-build-cmd',
'image': 'golang:1.17',
'image': go_image,
'commands': [
"go build -o ./bin/build -ldflags '-extldflags -static' ./pkg/build/cmd",
],

Loading…
Cancel
Save