Chore: Enable errorlint linter (#29227)

* Enable errorlint linter
* Handle wrapped errors

Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com>
Co-authored-by: Emil Tullstedt <emil.tullstedt@grafana.com>
This commit is contained in:
Arve Knudsen
2020-11-19 14:47:17 +01:00
committed by GitHub
parent 993adb72e0
commit 9593d57914
34 changed files with 142 additions and 101 deletions

View File

@ -4,6 +4,7 @@ import (
"bufio" "bufio"
"crypto/md5" "crypto/md5"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
@ -25,9 +26,8 @@ type GrafanaComClient struct {
func (client *GrafanaComClient) GetPlugin(pluginId, repoUrl string) (models.Plugin, error) { func (client *GrafanaComClient) GetPlugin(pluginId, repoUrl string) (models.Plugin, error) {
logger.Debugf("getting plugin metadata from: %v pluginId: %v \n", repoUrl, pluginId) logger.Debugf("getting plugin metadata from: %v pluginId: %v \n", repoUrl, pluginId)
body, err := sendRequestGetBytes(HttpClient, repoUrl, "repo", pluginId) body, err := sendRequestGetBytes(HttpClient, repoUrl, "repo", pluginId)
if err != nil { if err != nil {
if err == ErrNotFoundError { if errors.Is(err, ErrNotFoundError) {
return models.Plugin{}, errutil.Wrap("Failed to find requested plugin, check if the plugin_id is correct", err) return models.Plugin{}, errutil.Wrap("Failed to find requested plugin, check if the plugin_id is correct", err)
} }
return models.Plugin{}, errutil.Wrap("Failed to send request", err) return models.Plugin{}, errutil.Wrap("Failed to send request", err)

View File

@ -2,6 +2,7 @@ package services
import ( import (
"bytes" "bytes"
"errors"
"io" "io"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
@ -74,8 +75,9 @@ func makeBody(body string) io.ReadCloser {
} }
func asBadRequestError(t *testing.T, err error) *BadRequestError { func asBadRequestError(t *testing.T, err error) *BadRequestError {
if badRequestError, ok := err.(*BadRequestError); ok { var badErr *BadRequestError
return badRequestError if errors.As(err, &badErr) {
return badErr
} }
assert.FailNow(t, "Error was not of type BadRequestError") assert.FailNow(t, "Error was not of type BadRequestError")
return nil return nil

View File

@ -2,6 +2,7 @@ package authproxy
import ( import (
"encoding/hex" "encoding/hex"
"errors"
"fmt" "fmt"
"hash/fnv" "hash/fnv"
"net" "net"
@ -180,12 +181,12 @@ func (auth *AuthProxy) Login(logger log.Logger, ignoreCache bool) (int64, *Error
} }
if isLDAPEnabled() { if isLDAPEnabled() {
id, e := auth.LoginViaLDAP() id, err := auth.LoginViaLDAP()
if e != nil { if err != nil {
if e == ldap.ErrInvalidCredentials { if errors.Is(err, ldap.ErrInvalidCredentials) {
return 0, newError("proxy authentication required", ldap.ErrInvalidCredentials) return 0, newError("proxy authentication required", ldap.ErrInvalidCredentials)
} }
return 0, newError("failed to get the user", e) return 0, newError("failed to get the user", err)
} }
return id, nil return id, nil

View File

@ -2,6 +2,7 @@ package middleware
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"net/url" "net/url"
"strconv" "strconv"
@ -182,7 +183,7 @@ func initContextWithBasicAuth(ctx *models.ReqContext, orgId int64) bool {
"err", err, "err", err,
) )
if err == models.ErrUserNotFound { if errors.Is(err, models.ErrUserNotFound) {
err = login.ErrInvalidCredentials err = login.ErrInvalidCredentials
} }
ctx.JsonApiErr(401, errStringInvalidUsernamePassword, err) ctx.JsonApiErr(401, errStringInvalidUsernamePassword, err)
@ -250,7 +251,7 @@ func rotateEndOfRequestFunc(ctx *models.ReqContext, authTokenService models.User
// if the request is cancelled by the client we should not try // if the request is cancelled by the client we should not try
// to rotate the token since the client would not accept any result. // to rotate the token since the client would not accept any result.
if ctx.Context.Req.Context().Err() == context.Canceled { if errors.Is(ctx.Context.Req.Context().Err(), context.Canceled) {
return return
} }

View File

@ -17,6 +17,7 @@ package middleware
import ( import (
"bytes" "bytes"
"errors"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
@ -102,7 +103,7 @@ func function(pc uintptr) []byte {
func Recovery() macaron.Handler { func Recovery() macaron.Handler {
return func(c *macaron.Context) { return func(c *macaron.Context) {
defer func() { defer func() {
if err := recover(); err != nil { if r := recover(); r != nil {
panicLogger := log.Root panicLogger := log.Root
// try to get request logger // try to get request logger
if ctx, ok := c.Data["ctx"]; ok { if ctx, ok := c.Data["ctx"]; ok {
@ -110,16 +111,18 @@ func Recovery() macaron.Handler {
panicLogger = ctxTyped.Logger panicLogger = ctxTyped.Logger
} }
// http.ErrAbortHandler is suppressed by default in the http package if err, ok := r.(error); ok {
// and used as a signal for aborting requests. Suppresses stacktrace // http.ErrAbortHandler is suppressed by default in the http package
// since it doesn't add any important information. // and used as a signal for aborting requests. Suppresses stacktrace
if err == http.ErrAbortHandler { // since it doesn't add any important information.
panicLogger.Error("Request error", "error", err) if errors.Is(err, http.ErrAbortHandler) {
return panicLogger.Error("Request error", "error", err)
return
}
} }
stack := stack(3) stack := stack(3)
panicLogger.Error("Request error", "error", err, "stack", string(stack)) panicLogger.Error("Request error", "error", r, "stack", string(stack))
// if response has already been written, skip. // if response has already been written, skip.
if c.Written() { if c.Written() {
@ -131,8 +134,8 @@ func Recovery() macaron.Handler {
c.Data["Theme"] = setting.DefaultTheme c.Data["Theme"] = setting.DefaultTheme
if setting.Env == setting.Dev { if setting.Env == setting.Dev {
if theErr, ok := err.(error); ok { if err, ok := r.(error); ok {
c.Data["Title"] = theErr.Error() c.Data["Title"] = err.Error()
} }
c.Data["ErrorMsg"] = string(stack) c.Data["ErrorMsg"] = string(stack)

View File

@ -1,6 +1,7 @@
package conditions package conditions
import ( import (
"errors"
"fmt" "fmt"
"strings" "strings"
"time" "time"
@ -158,7 +159,7 @@ func (c *QueryCondition) executeQuery(context *alerting.EvalContext, timeRange *
resp, err := c.HandleRequest(context.Ctx, getDsInfo.Result, req) resp, err := c.HandleRequest(context.Ctx, getDsInfo.Result, req)
if err != nil { if err != nil {
if err == gocontext.DeadlineExceeded { if errors.Is(err, gocontext.DeadlineExceeded) {
return nil, fmt.Errorf("alert execution exceeded the timeout") return nil, fmt.Errorf("alert execution exceeded the timeout")
} }

View File

@ -167,7 +167,7 @@ func (e *DashAlertExtractor) getAlertFromPanels(jsonWithPanels *simplejson.Json,
} }
if err := bus.Dispatch(&dsFilterQuery); err != nil { if err := bus.Dispatch(&dsFilterQuery); err != nil {
if err != bus.ErrHandlerNotFound { if !errors.Is(err, bus.ErrHandlerNotFound) {
return nil, err return nil, err
} }
} else { } else {

View File

@ -2,6 +2,7 @@ package alerting
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"time" "time"
@ -159,11 +160,11 @@ func (n *notificationService) sendNotification(evalContext *EvalContext, notifie
} }
err := bus.DispatchCtx(evalContext.Ctx, setPendingCmd) err := bus.DispatchCtx(evalContext.Ctx, setPendingCmd)
if err == models.ErrAlertNotificationStateVersionConflict {
return nil
}
if err != nil { if err != nil {
if errors.Is(err, models.ErrAlertNotificationStateVersionConflict) {
return nil
}
return err return err
} }

View File

@ -1,6 +1,7 @@
package notifiers package notifiers
import ( import (
"errors"
"testing" "testing"
"github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/components/simplejson"
@ -70,7 +71,9 @@ func TestThreemaNotifier(t *testing.T) {
not, err := NewThreemaNotifier(model) not, err := NewThreemaNotifier(model)
So(not, ShouldBeNil) So(not, ShouldBeNil)
So(err.(alerting.ValidationError).Reason, ShouldEqual, "Invalid Threema Gateway ID: Must start with a *") var valErr alerting.ValidationError
So(errors.As(err, &valErr), ShouldBeTrue)
So(valErr.Reason, ShouldEqual, "Invalid Threema Gateway ID: Must start with a *")
}) })
Convey("invalid Threema Gateway IDs should be rejected (length)", func() { Convey("invalid Threema Gateway IDs should be rejected (length)", func() {
@ -90,7 +93,9 @@ func TestThreemaNotifier(t *testing.T) {
not, err := NewThreemaNotifier(model) not, err := NewThreemaNotifier(model)
So(not, ShouldBeNil) So(not, ShouldBeNil)
So(err.(alerting.ValidationError).Reason, ShouldEqual, "Invalid Threema Gateway ID: Must be 8 characters long") var valErr alerting.ValidationError
So(errors.As(err, &valErr), ShouldBeTrue)
So(valErr.Reason, ShouldEqual, "Invalid Threema Gateway ID: Must be 8 characters long")
}) })
Convey("invalid Threema Recipient IDs should be rejected (length)", func() { Convey("invalid Threema Recipient IDs should be rejected (length)", func() {
@ -110,7 +115,9 @@ func TestThreemaNotifier(t *testing.T) {
not, err := NewThreemaNotifier(model) not, err := NewThreemaNotifier(model)
So(not, ShouldBeNil) So(not, ShouldBeNil)
So(err.(alerting.ValidationError).Reason, ShouldEqual, "Invalid Threema Recipient ID: Must be 8 characters long") var valErr alerting.ValidationError
So(errors.As(err, &valErr), ShouldBeTrue)
So(valErr.Reason, ShouldEqual, "Invalid Threema Recipient ID: Must be 8 characters long")
}) })
}) })
}) })

View File

@ -59,12 +59,12 @@ func (handler *defaultResultHandler) handle(evalContext *EvalContext) error {
} }
if err := bus.Dispatch(cmd); err != nil { if err := bus.Dispatch(cmd); err != nil {
if err == models.ErrCannotChangeStateOnPausedAlert { if errors.Is(err, models.ErrCannotChangeStateOnPausedAlert) {
handler.log.Error("Cannot change state on alert that's paused", "error", err) handler.log.Error("Cannot change state on alert that's paused", "error", err)
return err return err
} }
if err == models.ErrRequiresNewState { if errors.Is(err, models.ErrRequiresNewState) {
handler.log.Info("Alert already updated") handler.log.Info("Alert already updated")
return nil return nil
} }

View File

@ -7,6 +7,8 @@ import (
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/sqlstore" "github.com/grafana/grafana/pkg/services/sqlstore"
. "github.com/smartystreets/goconvey/convey" . "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
type FakeCondition struct{} type FakeCondition struct{}
@ -34,15 +36,15 @@ func TestAlertRuleFrequencyParsing(t *testing.T) {
} }
for _, tc := range tcs { for _, tc := range tcs {
r, err := getTimeDurationStringToSeconds(tc.input) t.Run(tc.input, func(t *testing.T) {
if err != tc.err { r, err := getTimeDurationStringToSeconds(tc.input)
t.Errorf("expected error: '%v' got: '%v'", tc.err, err) if tc.err == nil {
return require.NoError(t, err)
} } else {
require.EqualError(t, err, tc.err.Error())
if r != tc.result { }
t.Errorf("expected result: %d got %d", tc.result, r) assert.Equal(t, tc.result, r)
} })
} }
} }

View File

@ -1,6 +1,8 @@
package dashboards package dashboards
import ( import (
"errors"
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/guardian" "github.com/grafana/grafana/pkg/services/guardian"
@ -209,31 +211,31 @@ func dashToFolder(dash *models.Dashboard) *models.Folder {
} }
func toFolderError(err error) error { func toFolderError(err error) error {
if err == models.ErrDashboardTitleEmpty { if errors.Is(err, models.ErrDashboardTitleEmpty) {
return models.ErrFolderTitleEmpty return models.ErrFolderTitleEmpty
} }
if err == models.ErrDashboardUpdateAccessDenied { if errors.Is(err, models.ErrDashboardUpdateAccessDenied) {
return models.ErrFolderAccessDenied return models.ErrFolderAccessDenied
} }
if err == models.ErrDashboardWithSameNameInFolderExists { if errors.Is(err, models.ErrDashboardWithSameNameInFolderExists) {
return models.ErrFolderSameNameExists return models.ErrFolderSameNameExists
} }
if err == models.ErrDashboardWithSameUIDExists { if errors.Is(err, models.ErrDashboardWithSameUIDExists) {
return models.ErrFolderWithSameUIDExists return models.ErrFolderWithSameUIDExists
} }
if err == models.ErrDashboardVersionMismatch { if errors.Is(err, models.ErrDashboardVersionMismatch) {
return models.ErrFolderVersionMismatch return models.ErrFolderVersionMismatch
} }
if err == models.ErrDashboardNotFound { if errors.Is(err, models.ErrDashboardNotFound) {
return models.ErrFolderNotFound return models.ErrFolderNotFound
} }
if err == models.ErrDashboardFailedGenerateUniqueUid { if errors.Is(err, models.ErrDashboardFailedGenerateUniqueUid) {
err = models.ErrFolderFailedGenerateUniqueUid err = models.ErrFolderFailedGenerateUniqueUid
} }

View File

@ -5,6 +5,7 @@ import (
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/stretchr/testify/assert"
"github.com/grafana/grafana/pkg/services/guardian" "github.com/grafana/grafana/pkg/services/guardian"
@ -194,9 +195,8 @@ func TestFolderService(t *testing.T) {
for _, tc := range testCases { for _, tc := range testCases {
actualError := toFolderError(tc.ActualError) actualError := toFolderError(tc.ActualError)
if actualError != tc.ExpectedError { assert.EqualErrorf(t, actualError, tc.ExpectedError.Error(),
t.Errorf("For error '%s' expected error '%s', actual '%s'", tc.ActualError, tc.ExpectedError, actualError) "For error '%s' expected error '%s', actual '%s'", tc.ActualError, tc.ExpectedError, actualError)
}
} }
}) })
}) })

View File

@ -1,6 +1,7 @@
package guardian package guardian
import ( import (
"errors"
"fmt" "fmt"
"runtime" "runtime"
"testing" "testing"
@ -300,7 +301,7 @@ func (sc *scenarioContext) verifyDuplicatePermissionsShouldNotBeAllowed() {
sc.updatePermissions = p sc.updatePermissions = p
_, err := sc.g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, p) _, err := sc.g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, p)
if err != ErrGuardianPermissionExists { if !errors.Is(err, ErrGuardianPermissionExists) {
sc.reportFailure(tc, ErrGuardianPermissionExists, err) sc.reportFailure(tc, ErrGuardianPermissionExists, err)
} }
sc.reportSuccess() sc.reportSuccess()
@ -314,8 +315,7 @@ func (sc *scenarioContext) verifyDuplicatePermissionsShouldNotBeAllowed() {
} }
sc.updatePermissions = p sc.updatePermissions = p
_, err := sc.g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, p) _, err := sc.g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, p)
if !errors.Is(err, ErrGuardianPermissionExists) {
if err != ErrGuardianPermissionExists {
sc.reportFailure(tc, ErrGuardianPermissionExists, err) sc.reportFailure(tc, ErrGuardianPermissionExists, err)
} }
sc.reportSuccess() sc.reportSuccess()
@ -330,7 +330,7 @@ func (sc *scenarioContext) verifyDuplicatePermissionsShouldNotBeAllowed() {
sc.updatePermissions = p sc.updatePermissions = p
_, err := sc.g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, p) _, err := sc.g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, p)
if err != ErrGuardianPermissionExists { if !errors.Is(err, ErrGuardianPermissionExists) {
sc.reportFailure(tc, ErrGuardianPermissionExists, err) sc.reportFailure(tc, ErrGuardianPermissionExists, err)
} }
sc.reportSuccess() sc.reportSuccess()
@ -344,8 +344,7 @@ func (sc *scenarioContext) verifyDuplicatePermissionsShouldNotBeAllowed() {
} }
sc.updatePermissions = p sc.updatePermissions = p
_, err := sc.g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, p) _, err := sc.g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, p)
if !errors.Is(err, ErrGuardianPermissionExists) {
if err != ErrGuardianPermissionExists {
sc.reportFailure(tc, ErrGuardianPermissionExists, err) sc.reportFailure(tc, ErrGuardianPermissionExists, err)
} }
sc.reportSuccess() sc.reportSuccess()
@ -358,8 +357,7 @@ func (sc *scenarioContext) verifyDuplicatePermissionsShouldNotBeAllowed() {
} }
sc.updatePermissions = p sc.updatePermissions = p
_, err := sc.g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, p) _, err := sc.g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, p)
if !errors.Is(err, ErrGuardianPermissionExists) {
if err != ErrGuardianPermissionExists {
sc.reportFailure(tc, ErrGuardianPermissionExists, err) sc.reportFailure(tc, ErrGuardianPermissionExists, err)
} }
sc.reportSuccess() sc.reportSuccess()
@ -402,7 +400,6 @@ func (sc *scenarioContext) verifyUpdateDashboardPermissionsShouldBeAllowed(pt pe
sc.updatePermissions = permissionList sc.updatePermissions = permissionList
ok, err := sc.g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, permissionList) ok, err := sc.g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, permissionList)
if err != nil { if err != nil {
sc.reportFailure(tc, nil, err) sc.reportFailure(tc, nil, err)
} }
@ -442,7 +439,6 @@ func (sc *scenarioContext) verifyUpdateDashboardPermissionsShouldNotBeAllowed(pt
sc.updatePermissions = permissionList sc.updatePermissions = permissionList
ok, err := sc.g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, permissionList) ok, err := sc.g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, permissionList)
if err != nil { if err != nil {
sc.reportFailure(tc, nil, err) sc.reportFailure(tc, nil, err)
} }
@ -505,7 +501,6 @@ func (sc *scenarioContext) verifyUpdateChildDashboardPermissionsShouldBeAllowed(
sc.updatePermissions = permissionList sc.updatePermissions = permissionList
ok, err := sc.g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, permissionList) ok, err := sc.g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, permissionList)
if err != nil { if err != nil {
sc.reportFailure(tc, nil, err) sc.reportFailure(tc, nil, err)
} }
@ -568,7 +563,6 @@ func (sc *scenarioContext) verifyUpdateChildDashboardPermissionsShouldNotBeAllow
sc.updatePermissions = permissionList sc.updatePermissions = permissionList
ok, err := sc.g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, permissionList) ok, err := sc.g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, permissionList)
if err != nil { if err != nil {
sc.reportFailure(tc, nil, err) sc.reportFailure(tc, nil, err)
} }
@ -616,8 +610,7 @@ func (sc *scenarioContext) verifyUpdateChildDashboardPermissionsWithOverrideShou
sc.updatePermissions = permissionList sc.updatePermissions = permissionList
_, err := sc.g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, permissionList) _, err := sc.g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, permissionList)
if !errors.Is(err, ErrGuardianOverride) {
if err != ErrGuardianOverride {
sc.reportFailure(tc, ErrGuardianOverride, err) sc.reportFailure(tc, ErrGuardianOverride, err)
} }
sc.reportSuccess() sc.reportSuccess()
@ -665,7 +658,6 @@ func (sc *scenarioContext) verifyUpdateChildDashboardPermissionsWithOverrideShou
} }
sc.updatePermissions = permissionList sc.updatePermissions = permissionList
ok, err := sc.g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, permissionList) ok, err := sc.g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, permissionList)
if err != nil { if err != nil {
sc.reportFailure(tc, nil, err) sc.reportFailure(tc, nil, err)
} }

View File

@ -475,11 +475,11 @@ func (server *Server) AdminBind() error {
func (server *Server) userBind(path, password string) error { func (server *Server) userBind(path, password string) error {
err := server.Connection.Bind(path, password) err := server.Connection.Bind(path, password)
if err != nil { if err != nil {
if ldapErr, ok := err.(*ldap.Error); ok { var ldapErr *ldap.Error
if ldapErr.ResultCode == 49 { if errors.As(err, &ldapErr) && ldapErr.ResultCode == 49 {
return ErrInvalidCredentials return ErrInvalidCredentials
}
} }
return err return err
} }

View File

@ -234,7 +234,7 @@ func isSilentError(err error) bool {
continueErrs := []error{ErrInvalidCredentials, ErrCouldNotFindUser} continueErrs := []error{ErrInvalidCredentials, ErrCouldNotFindUser}
for _, cerr := range continueErrs { for _, cerr := range continueErrs {
if err == cerr { if errors.Is(err, cerr) {
return true return true
} }
} }

View File

@ -2,6 +2,7 @@ package oauthtoken
import ( import (
"context" "context"
"errors"
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/log"
@ -23,7 +24,7 @@ func GetCurrentOAuthToken(ctx context.Context, user *models.SignedInUser) *oauth
authInfoQuery := &models.GetAuthInfoQuery{UserId: user.UserId} authInfoQuery := &models.GetAuthInfoQuery{UserId: user.UserId}
if err := bus.Dispatch(authInfoQuery); err != nil { if err := bus.Dispatch(authInfoQuery); err != nil {
if err == models.ErrUserNotFound { if errors.Is(err, models.ErrUserNotFound) {
// Not necessarily an error. User may be logged in another way. // Not necessarily an error. User may be logged in another way.
logger.Debug("no OAuth token for user found", "userId", user.UserId, "username", user.Login) logger.Debug("no OAuth token for user found", "userId", user.UserId, "username", user.Login)
} else { } else {

View File

@ -117,8 +117,7 @@ func (fr *FileReader) startWalkingDisk() error {
// storeDashboardsInFolder saves dashboards from the filesystem on disk to the folder from config // storeDashboardsInFolder saves dashboards from the filesystem on disk to the folder from config
func (fr *FileReader) storeDashboardsInFolder(filesFoundOnDisk map[string]os.FileInfo, dashboardRefs map[string]*models.DashboardProvisioning, sanityChecker *provisioningSanityChecker) error { func (fr *FileReader) storeDashboardsInFolder(filesFoundOnDisk map[string]os.FileInfo, dashboardRefs map[string]*models.DashboardProvisioning, sanityChecker *provisioningSanityChecker) error {
folderID, err := getOrCreateFolderID(fr.Cfg, fr.dashboardProvisioningService, fr.Cfg.Folder) folderID, err := getOrCreateFolderID(fr.Cfg, fr.dashboardProvisioningService, fr.Cfg.Folder)
if err != nil && !errors.Is(err, ErrFolderNameMissing) {
if err != nil && err != ErrFolderNameMissing {
return err return err
} }
@ -145,7 +144,7 @@ func (fr *FileReader) storeDashboardsInFoldersFromFileStructure(filesFoundOnDisk
} }
folderID, err := getOrCreateFolderID(fr.Cfg, fr.dashboardProvisioningService, folderName) folderID, err := getOrCreateFolderID(fr.Cfg, fr.dashboardProvisioningService, folderName)
if err != nil && err != ErrFolderNameMissing { if err != nil && !errors.Is(err, ErrFolderNameMissing) {
return fmt.Errorf("can't provision folder %q from file system structure: %w", folderName, err) return fmt.Errorf("can't provision folder %q from file system structure: %w", folderName, err)
} }
@ -264,12 +263,12 @@ func getOrCreateFolderID(cfg *config, service dashboards.DashboardProvisioningSe
cmd := &models.GetDashboardQuery{Slug: models.SlugifyTitle(folderName), OrgId: cfg.OrgID} cmd := &models.GetDashboardQuery{Slug: models.SlugifyTitle(folderName), OrgId: cfg.OrgID}
err := bus.Dispatch(cmd) err := bus.Dispatch(cmd)
if err != nil && err != models.ErrDashboardNotFound { if err != nil && !errors.Is(err, models.ErrDashboardNotFound) {
return 0, err return 0, err
} }
// dashboard folder not found. create one. // dashboard folder not found. create one.
if err == models.ErrDashboardNotFound { if errors.Is(err, models.ErrDashboardNotFound) {
dash := &dashboards.SaveDashboardDTO{} dash := &dashboards.SaveDashboardDTO{}
dash.Dashboard = models.NewDashboardFolder(folderName) dash.Dashboard = models.NewDashboardFolder(folderName)
dash.Dashboard.IsFolder = true dash.Dashboard.IsFolder = true

View File

@ -45,11 +45,11 @@ func (dc *DatasourceProvisioner) apply(cfg *configs) error {
for _, ds := range cfg.Datasources { for _, ds := range cfg.Datasources {
cmd := &models.GetDataSourceByNameQuery{OrgId: ds.OrgID, Name: ds.Name} cmd := &models.GetDataSourceByNameQuery{OrgId: ds.OrgID, Name: ds.Name}
err := bus.Dispatch(cmd) err := bus.Dispatch(cmd)
if err != nil && err != models.ErrDataSourceNotFound { if err != nil && !errors.Is(err, models.ErrDataSourceNotFound) {
return err return err
} }
if err == models.ErrDataSourceNotFound { if errors.Is(err, models.ErrDataSourceNotFound) {
dc.log.Info("inserting datasource from configuration ", "name", ds.Name, "uid", ds.UID) dc.log.Info("inserting datasource from configuration ", "name", ds.Name, "uid", ds.UID)
insertCmd := createInsertCommand(ds) insertCmd := createInsertCommand(ds)
if err := bus.Dispatch(insertCmd); err != nil { if err := bus.Dispatch(insertCmd); err != nil {

View File

@ -1,6 +1,8 @@
package plugins package plugins
import ( import (
"errors"
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
@ -42,7 +44,7 @@ func (ap *PluginProvisioner) apply(cfg *pluginsAsConfig) error {
query := &models.GetPluginSettingByIdQuery{OrgId: app.OrgID, PluginId: app.PluginID} query := &models.GetPluginSettingByIdQuery{OrgId: app.OrgID, PluginId: app.PluginID}
err := bus.Dispatch(query) err := bus.Dispatch(query)
if err != nil { if err != nil {
if err != models.ErrPluginSettingNotFound { if !errors.Is(err, models.ErrPluginSettingNotFound) {
return err return err
} }
} else { } else {

View File

@ -2,6 +2,7 @@ package rendering
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"io" "io"
"net" "net"
@ -79,7 +80,7 @@ func (rs *RenderingService) renderViaHttp(ctx context.Context, renderKey string,
defer resp.Body.Close() defer resp.Body.Close()
// check for timeout first // check for timeout first
if reqContext.Err() == context.DeadlineExceeded { if errors.Is(reqContext.Err(), context.DeadlineExceeded) {
rs.log.Info("Rendering timed out") rs.log.Info("Rendering timed out")
return nil, ErrTimeout return nil, ErrTimeout
} }
@ -99,7 +100,7 @@ func (rs *RenderingService) renderViaHttp(ctx context.Context, renderKey string,
_, err = io.Copy(out, resp.Body) _, err = io.Copy(out, resp.Body)
if err != nil { if err != nil {
// check that we didn't timeout while receiving the response. // check that we didn't timeout while receiving the response.
if reqContext.Err() == context.DeadlineExceeded { if errors.Is(reqContext.Err(), context.DeadlineExceeded) {
rs.log.Info("Rendering timed out") rs.log.Info("Rendering timed out")
return nil, ErrTimeout return nil, ErrTimeout
} }

View File

@ -2,6 +2,7 @@ package rendering
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"time" "time"
@ -45,7 +46,7 @@ func (rs *RenderingService) renderViaPluginV1(ctx context.Context, renderKey str
rs.log.Debug("calling renderer plugin", "req", req) rs.log.Debug("calling renderer plugin", "req", req)
rsp, err := rs.pluginInfo.GrpcPluginV1.Render(ctx, req) rsp, err := rs.pluginInfo.GrpcPluginV1.Render(ctx, req)
if ctx.Err() == context.DeadlineExceeded { if errors.Is(ctx.Err(), context.DeadlineExceeded) {
rs.log.Info("Rendering timed out") rs.log.Info("Rendering timed out")
return nil, ErrTimeout return nil, ErrTimeout
} }
@ -88,7 +89,7 @@ func (rs *RenderingService) renderViaPluginV2(ctx context.Context, renderKey str
rs.log.Debug("Calling renderer plugin", "req", req) rs.log.Debug("Calling renderer plugin", "req", req)
rsp, err := rs.pluginInfo.GrpcPluginV2.Render(ctx, req) rsp, err := rs.pluginInfo.GrpcPluginV2.Render(ctx, req)
if ctx.Err() == context.DeadlineExceeded { if errors.Is(ctx.Err(), context.DeadlineExceeded) {
rs.log.Info("Rendering timed out") rs.log.Info("Rendering timed out")
return nil, ErrTimeout return nil, ErrTimeout
} }

View File

@ -2,6 +2,7 @@ package rendering
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"math" "math"
"net/url" "net/url"
@ -136,7 +137,7 @@ func (rs *RenderingService) Render(ctx context.Context, opts Opts) (*RenderResul
elapsedTime := time.Since(startTime).Milliseconds() elapsedTime := time.Since(startTime).Milliseconds()
result, err := rs.render(ctx, opts) result, err := rs.render(ctx, opts)
if err != nil { if err != nil {
if err == ErrTimeout { if errors.Is(err, ErrTimeout) {
metrics.MRenderingRequestTotal.WithLabelValues("timeout").Inc() metrics.MRenderingRequestTotal.WithLabelValues("timeout").Inc()
metrics.MRenderingSummary.WithLabelValues("timeout").Observe(float64(elapsedTime)) metrics.MRenderingSummary.WithLabelValues("timeout").Observe(float64(elapsedTime))
} else { } else {

View File

@ -4,6 +4,7 @@ import (
"context" "context"
"database/sql" "database/sql"
"database/sql/driver" "database/sql/driver"
"errors"
"time" "time"
"github.com/gchaincl/sqlhooks" "github.com/gchaincl/sqlhooks"
@ -87,7 +88,7 @@ func (h *databaseQueryWrapper) After(ctx context.Context, query string, args ...
func (h *databaseQueryWrapper) OnError(ctx context.Context, err error, query string, args ...interface{}) error { func (h *databaseQueryWrapper) OnError(ctx context.Context, err error, query string, args ...interface{}) error {
status := "error" status := "error"
// https://golang.org/pkg/database/sql/driver/#ErrSkip // https://golang.org/pkg/database/sql/driver/#ErrSkip
if err == nil || err == driver.ErrSkip { if err == nil || errors.Is(err, driver.ErrSkip) {
status = "success" status = "success"
} }

View File

@ -1,6 +1,7 @@
package migrator package migrator
import ( import (
"errors"
"time" "time"
_ "github.com/go-sql-driver/mysql" _ "github.com/go-sql-driver/mysql"
@ -168,8 +169,8 @@ func (mg *Migrator) inTransaction(callback dbTransactionFunc) error {
} }
if err := callback(sess); err != nil { if err := callback(sess); err != nil {
if rollErr := sess.Rollback(); err != rollErr { if rollErr := sess.Rollback(); !errors.Is(err, rollErr) {
return errutil.Wrapf(err, "Failed to roll back transaction due to error: %s", rollErr) return errutil.Wrapf(err, "failed to roll back transaction due to error: %s", rollErr)
} }
return err return err

View File

@ -1,6 +1,7 @@
package migrator package migrator
import ( import (
"errors"
"fmt" "fmt"
"strconv" "strconv"
"strings" "strings"
@ -169,7 +170,8 @@ func (db *MySQLDialect) TruncateDBTables() error {
} }
func (db *MySQLDialect) isThisError(err error, errcode uint16) bool { func (db *MySQLDialect) isThisError(err error, errcode uint16) bool {
if driverErr, ok := err.(*mysql.MySQLError); ok { var driverErr *mysql.MySQLError
if errors.As(err, &driverErr) {
if driverErr.Number == errcode { if driverErr.Number == errcode {
return true return true
} }
@ -183,7 +185,8 @@ func (db *MySQLDialect) IsUniqueConstraintViolation(err error) bool {
} }
func (db *MySQLDialect) ErrorMessage(err error) string { func (db *MySQLDialect) ErrorMessage(err error) string {
if driverErr, ok := err.(*mysql.MySQLError); ok { var driverErr *mysql.MySQLError
if errors.As(err, &driverErr) {
return driverErr.Message return driverErr.Message
} }
return "" return ""

View File

@ -1,6 +1,7 @@
package migrator package migrator
import ( import (
"errors"
"fmt" "fmt"
"strconv" "strconv"
"strings" "strings"
@ -172,7 +173,8 @@ func (db *PostgresDialect) TruncateDBTables() error {
} }
func (db *PostgresDialect) isThisError(err error, errcode string) bool { func (db *PostgresDialect) isThisError(err error, errcode string) bool {
if driverErr, ok := err.(*pq.Error); ok { var driverErr *pq.Error
if errors.As(err, &driverErr) {
if string(driverErr.Code) == errcode { if string(driverErr.Code) == errcode {
return true return true
} }
@ -182,7 +184,8 @@ func (db *PostgresDialect) isThisError(err error, errcode string) bool {
} }
func (db *PostgresDialect) ErrorMessage(err error) string { func (db *PostgresDialect) ErrorMessage(err error) string {
if driverErr, ok := err.(*pq.Error); ok { var driverErr *pq.Error
if errors.As(err, &driverErr) {
return driverErr.Message return driverErr.Message
} }
return "" return ""

View File

@ -1,6 +1,7 @@
package migrator package migrator
import ( import (
"errors"
"fmt" "fmt"
"github.com/grafana/grafana/pkg/util/errutil" "github.com/grafana/grafana/pkg/util/errutil"
@ -120,7 +121,8 @@ func (db *SQLite3) TruncateDBTables() error {
} }
func (db *SQLite3) isThisError(err error, errcode int) bool { func (db *SQLite3) isThisError(err error, errcode int) bool {
if driverErr, ok := err.(sqlite3.Error); ok { var driverErr sqlite3.Error
if errors.As(err, &driverErr) {
if int(driverErr.ExtendedCode) == errcode { if int(driverErr.ExtendedCode) == errcode {
return true return true
} }
@ -130,7 +132,8 @@ func (db *SQLite3) isThisError(err error, errcode int) bool {
} }
func (db *SQLite3) ErrorMessage(err error) string { func (db *SQLite3) ErrorMessage(err error) string {
if driverErr, ok := err.(sqlite3.Error); ok { var driverErr sqlite3.Error
if errors.As(err, &driverErr) {
return driverErr.Error() return driverErr.Error()
} }
return "" return ""

View File

@ -2,6 +2,7 @@ package sqlstore
import ( import (
"context" "context"
"errors"
"time" "time"
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
@ -42,8 +43,8 @@ func inTransactionWithRetryCtx(ctx context.Context, engine *xorm.Engine, callbac
err = callback(sess) err = callback(sess)
// special handling of database locked errors for sqlite, then we can retry 5 times // special handling of database locked errors for sqlite, then we can retry 5 times
if sqlError, ok := err.(sqlite3.Error); ok && retry < 5 && sqlError.Code == var sqlError sqlite3.Error
sqlite3.ErrLocked || sqlError.Code == sqlite3.ErrBusy { if errors.As(err, &sqlError) && retry < 5 && sqlError.Code == sqlite3.ErrLocked || sqlError.Code == sqlite3.ErrBusy {
if rollErr := sess.Rollback(); rollErr != nil { if rollErr := sess.Rollback(); rollErr != nil {
return errutil.Wrapf(err, "Rolling back transaction due to error failed: %s", rollErr) return errutil.Wrapf(err, "Rolling back transaction due to error failed: %s", rollErr)
} }

View File

@ -2,6 +2,7 @@ package sqlstore
import ( import (
"encoding/base64" "encoding/base64"
"errors"
"time" "time"
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
@ -33,7 +34,7 @@ func GetUserByAuthInfo(query *models.GetUserByAuthInfoQuery) error {
authQuery.AuthId = query.AuthId authQuery.AuthId = query.AuthId
err = GetAuthInfo(authQuery) err = GetAuthInfo(authQuery)
if err != models.ErrUserNotFound { if !errors.Is(err, models.ErrUserNotFound) {
if err != nil { if err != nil {
return err return err
} }

View File

@ -2,6 +2,7 @@ package cloudwatch
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"sort" "sort"
@ -258,11 +259,11 @@ func (e *cloudWatchExecutor) executeStopQuery(ctx context.Context, logsClient cl
response, err := logsClient.StopQueryWithContext(ctx, queryInput) response, err := logsClient.StopQueryWithContext(ctx, queryInput)
if err != nil { if err != nil {
awsErr, ok := err.(awserr.Error)
// If the query has already stopped by the time CloudWatch receives the stop query request, // If the query has already stopped by the time CloudWatch receives the stop query request,
// an "InvalidParameterException" error is returned. For our purposes though the query has been // an "InvalidParameterException" error is returned. For our purposes though the query has been
// stopped, so we ignore the error. // stopped, so we ignore the error.
if ok && awsErr.Code() == "InvalidParameterException" { var awsErr awserr.Error
if errors.As(err, &awsErr) && awsErr.Code() == "InvalidParameterException" {
response = &cloudwatchlogs.StopQueryOutput{Success: aws.Bool(false)} response = &cloudwatchlogs.StopQueryOutput{Success: aws.Bool(false)}
err = nil err = nil
} }

View File

@ -140,8 +140,10 @@ func (t *mysqlQueryResultTransformer) TransformQueryResult(columnTypes []*sql.Co
} }
func (t *mysqlQueryResultTransformer) TransformQueryError(err error) error { func (t *mysqlQueryResultTransformer) TransformQueryError(err error) error {
if driverErr, ok := err.(*mysql.MySQLError); ok { var driverErr *mysql.MySQLError
if driverErr.Number != mysqlerr.ER_PARSE_ERROR && driverErr.Number != mysqlerr.ER_BAD_FIELD_ERROR && driverErr.Number != mysqlerr.ER_NO_SUCH_TABLE { if errors.As(err, &driverErr) {
if driverErr.Number != mysqlerr.ER_PARSE_ERROR && driverErr.Number != mysqlerr.ER_BAD_FIELD_ERROR &&
driverErr.Number != mysqlerr.ER_NO_SUCH_TABLE {
t.log.Error("query error", "err", err) t.log.Error("query error", "err", err)
return errQueryFailed return errQueryFailed
} }

View File

@ -50,7 +50,7 @@ func walk(path string, info os.FileInfo, resolvedPath string, symlinkPathsFollow
} }
err := walkFn(resolvedPath, info, nil) err := walkFn(resolvedPath, info, nil)
if err != nil { if err != nil {
if info.IsDir() && err == ErrWalkSkipDir { if info.IsDir() && errors.Is(err, ErrWalkSkipDir) {
err = nil err = nil
} }
return err return err

View File

@ -39,6 +39,10 @@ enable = [
"varcheck", "varcheck",
"whitespace", "whitespace",
"gocyclo", "gocyclo",
"typecheck",
"asciicheck",
"errorlint",
"sqlclosecheck",
] ]
# Disabled linters (might want them later) # Disabled linters (might want them later)
@ -95,3 +99,7 @@ text = "404"
[[issues.exclude-rules]] [[issues.exclude-rules]]
linters = ["misspell"] linters = ["misspell"]
text = "Unknwon` is a misspelling of `Unknown" text = "Unknwon` is a misspelling of `Unknown"
[[issues.exclude-rules]]
linters = ["errorlint"]
text = "non-wrapping format verb for fmt.Errorf"