Commit 7897c6b7 by Arve Knudsen Committed by GitHub

Chore: Fix staticcheck issues (#28854)

* Chore: Fix issues reported by staticcheck

Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com>

* Undo changes

Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com>
parent 9b90ff29
...@@ -509,7 +509,7 @@ func TestPostSyncUserWithLDAPAPIEndpoint_WhenGrafanaAdmin(t *testing.T) { ...@@ -509,7 +509,7 @@ func TestPostSyncUserWithLDAPAPIEndpoint_WhenGrafanaAdmin(t *testing.T) {
expected := ` expected := `
{ {
"error": "Did not find a user", "error": "did not find a user",
"message": "Refusing to sync grafana super admin \"ldap-daniel\" - it would be disabled" "message": "Refusing to sync grafana super admin \"ldap-daniel\" - it would be disabled"
} }
` `
......
...@@ -35,12 +35,12 @@ type thresholdEvaluator struct { ...@@ -35,12 +35,12 @@ type thresholdEvaluator struct {
func newThresholdEvaluator(typ string, model *simplejson.Json) (*thresholdEvaluator, error) { func newThresholdEvaluator(typ string, model *simplejson.Json) (*thresholdEvaluator, error) {
params := model.Get("params").MustArray() params := model.Get("params").MustArray()
if len(params) == 0 || params[0] == nil { if len(params) == 0 || params[0] == nil {
return nil, fmt.Errorf("Evaluator '%v' is missing the threshold parameter", HumanThresholdType(typ)) return nil, fmt.Errorf("evaluator '%v' is missing the threshold parameter", HumanThresholdType(typ))
} }
firstParam, ok := params[0].(json.Number) firstParam, ok := params[0].(json.Number)
if !ok { if !ok {
return nil, fmt.Errorf("Evaluator has invalid parameter") return nil, fmt.Errorf("evaluator has invalid parameter")
} }
defaultEval := &thresholdEvaluator{Type: typ} defaultEval := &thresholdEvaluator{Type: typ}
...@@ -113,7 +113,7 @@ func (e *rangedEvaluator) Eval(reducedValue null.Float) bool { ...@@ -113,7 +113,7 @@ func (e *rangedEvaluator) Eval(reducedValue null.Float) bool {
func NewAlertEvaluator(model *simplejson.Json) (AlertEvaluator, error) { func NewAlertEvaluator(model *simplejson.Json) (AlertEvaluator, error) {
typ := model.Get("type").MustString() typ := model.Get("type").MustString()
if typ == "" { if typ == "" {
return nil, fmt.Errorf("Evaluator missing type property") return nil, fmt.Errorf("evaluator missing type property")
} }
if inSlice(typ, defaultTypes) { if inSlice(typ, defaultTypes) {
...@@ -128,7 +128,7 @@ func NewAlertEvaluator(model *simplejson.Json) (AlertEvaluator, error) { ...@@ -128,7 +128,7 @@ func NewAlertEvaluator(model *simplejson.Json) (AlertEvaluator, error) {
return &noValueEvaluator{}, nil return &noValueEvaluator{}, nil
} }
return nil, fmt.Errorf("Evaluator invalid evaluator type: %s", typ) return nil, fmt.Errorf("evaluator invalid evaluator type: %s", typ)
} }
func inSlice(a string, list []string) bool { func inSlice(a string, list []string) bool {
......
...@@ -113,7 +113,7 @@ func (c *QueryCondition) executeQuery(context *alerting.EvalContext, timeRange * ...@@ -113,7 +113,7 @@ func (c *QueryCondition) executeQuery(context *alerting.EvalContext, timeRange *
} }
if err := bus.Dispatch(getDsInfo); err != nil { if err := bus.Dispatch(getDsInfo); err != nil {
return nil, fmt.Errorf("Could not find datasource %v", err) return nil, fmt.Errorf("could not find datasource: %w", err)
} }
req := c.getRequestForAlertRule(getDsInfo.Result, timeRange, context.IsDebug) req := c.getRequestForAlertRule(getDsInfo.Result, timeRange, context.IsDebug)
...@@ -159,7 +159,7 @@ func (c *QueryCondition) executeQuery(context *alerting.EvalContext, timeRange * ...@@ -159,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 err == gocontext.DeadlineExceeded {
return nil, fmt.Errorf("Alert execution exceeded the timeout") return nil, fmt.Errorf("alert execution exceeded the timeout")
} }
return nil, fmt.Errorf("tsdb.HandleRequest() error %v", err) return nil, fmt.Errorf("tsdb.HandleRequest() error %v", err)
......
...@@ -2,7 +2,6 @@ package alerting ...@@ -2,7 +2,6 @@ package alerting
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"time" "time"
...@@ -281,7 +280,7 @@ func (n *notificationService) getNeededNotifiers(orgID int64, notificationUids [ ...@@ -281,7 +280,7 @@ func (n *notificationService) getNeededNotifiers(orgID int64, notificationUids [
func InitNotifier(model *models.AlertNotification) (Notifier, error) { func InitNotifier(model *models.AlertNotification) (Notifier, error) {
notifierPlugin, found := notifierFactories[model.Type] notifierPlugin, found := notifierFactories[model.Type]
if !found { if !found {
return nil, errors.New("Unsupported notification type") return nil, fmt.Errorf("unsupported notification type %q", model.Type)
} }
return notifierPlugin.Factory(model) return notifierPlugin.Factory(model)
......
...@@ -89,7 +89,7 @@ func createTestEvalContext(cmd *NotificationTestCommand) *EvalContext { ...@@ -89,7 +89,7 @@ func createTestEvalContext(cmd *NotificationTestCommand) *EvalContext {
} }
ctx.IsTestRun = true ctx.IsTestRun = true
ctx.Firing = true ctx.Firing = true
ctx.Error = fmt.Errorf("This is only a test") ctx.Error = fmt.Errorf("this is only a test")
ctx.EvalMatches = evalMatchesBasedOnState() ctx.EvalMatches = evalMatchesBasedOnState()
return ctx return ctx
......
...@@ -45,7 +45,7 @@ func handleAlertTestCommand(cmd *AlertTestCommand) error { ...@@ -45,7 +45,7 @@ func handleAlertTestCommand(cmd *AlertTestCommand) error {
} }
} }
return fmt.Errorf("Could not find alert with panel id %d", cmd.PanelID) return fmt.Errorf("could not find alert with panel ID %d", cmd.PanelID)
} }
func testAlertRule(rule *Rule) *EvalContext { func testAlertRule(rule *Rule) *EvalContext {
......
...@@ -10,8 +10,8 @@ import ( ...@@ -10,8 +10,8 @@ import (
) )
var ( var (
ErrGuardianPermissionExists = errors.New("Permission already exists") ErrGuardianPermissionExists = errors.New("permission already exists")
ErrGuardianOverride = errors.New("You can only override a permission to be higher") ErrGuardianOverride = errors.New("you can only override a permission to be higher")
) )
// DashboardGuardian to be used for guard against operations without access on dashboard and acl // DashboardGuardian to be used for guard against operations without access on dashboard and acl
......
...@@ -73,10 +73,10 @@ const UsersMaxRequest = 500 ...@@ -73,10 +73,10 @@ const UsersMaxRequest = 500
var ( var (
// ErrInvalidCredentials is returned if username and password do not match // ErrInvalidCredentials is returned if username and password do not match
ErrInvalidCredentials = errors.New("Invalid Username or Password") ErrInvalidCredentials = errors.New("invalid username or password")
// ErrCouldNotFindUser is returned when username hasn't been found (not username+password) // ErrCouldNotFindUser is returned when username hasn't been found (not username+password)
ErrCouldNotFindUser = errors.New("Can't find user in LDAP") ErrCouldNotFindUser = errors.New("can't find user in LDAP")
) )
// New creates the new LDAP connection // New creates the new LDAP connection
......
...@@ -3,7 +3,7 @@ package login ...@@ -3,7 +3,7 @@ package login
import "errors" import "errors"
var ( var (
ErrInvalidCredentials = errors.New("Invalid Username or Password") ErrInvalidCredentials = errors.New("invalid username or password")
ErrUsersQuotaReached = errors.New("Users quota reached") ErrUsersQuotaReached = errors.New("users quota reached")
ErrGettingUserQuota = errors.New("Error getting user quota") ErrGettingUserQuota = errors.New("error getting user quota")
) )
...@@ -27,10 +27,10 @@ var ErrInvalidCredentials = ldap.ErrInvalidCredentials ...@@ -27,10 +27,10 @@ var ErrInvalidCredentials = ldap.ErrInvalidCredentials
var ErrCouldNotFindUser = ldap.ErrCouldNotFindUser var ErrCouldNotFindUser = ldap.ErrCouldNotFindUser
// ErrNoLDAPServers is returned when there is no LDAP servers specified // ErrNoLDAPServers is returned when there is no LDAP servers specified
var ErrNoLDAPServers = errors.New("No LDAP servers are configured") var ErrNoLDAPServers = errors.New("no LDAP servers are configured")
// ErrDidNotFindUser if request for user is unsuccessful // ErrDidNotFindUser if request for user is unsuccessful
var ErrDidNotFindUser = errors.New("Did not find a user") var ErrDidNotFindUser = errors.New("did not find a user")
// ServerStatus holds the LDAP server status // ServerStatus holds the LDAP server status
type ServerStatus struct { type ServerStatus struct {
......
...@@ -109,12 +109,12 @@ func (ng *AlertNG) LoadAlertCondition(dashboardID int64, panelID int64, conditio ...@@ -109,12 +109,12 @@ func (ng *AlertNG) LoadAlertCondition(dashboardID int64, panelID int64, conditio
blob, err := getDashboardQuery.Result.Data.MarshalJSON() blob, err := getDashboardQuery.Result.Data.MarshalJSON()
if err != nil { if err != nil {
return nil, errors.New("Failed to marshal dashboard JSON") return nil, errors.New("failed to marshal dashboard JSON")
} }
var dash minimalDashboard var dash minimalDashboard
err = json.Unmarshal(blob, &dash) err = json.Unmarshal(blob, &dash)
if err != nil { if err != nil {
return nil, errors.New("Failed to unmarshal dashboard JSON") return nil, errors.New("failed to unmarshal dashboard JSON")
} }
condition := Condition{} condition := Condition{}
...@@ -144,7 +144,7 @@ func (ng *AlertNG) LoadAlertCondition(dashboardID int64, panelID int64, conditio ...@@ -144,7 +144,7 @@ func (ng *AlertNG) LoadAlertCondition(dashboardID int64, panelID int64, conditio
} }
if ds == nil { if ds == nil {
return nil, errors.New("No datasource reference found") return nil, errors.New("no datasource reference found")
} }
if queryDatasource == "" { if queryDatasource == "" {
...@@ -192,7 +192,7 @@ func (ng *AlertNG) LoadAlertCondition(dashboardID int64, panelID int64, conditio ...@@ -192,7 +192,7 @@ func (ng *AlertNG) LoadAlertCondition(dashboardID int64, panelID int64, conditio
func (c *Condition) Execute(ctx AlertExecCtx, fromStr, toStr string) (*ExecutionResults, error) { func (c *Condition) Execute(ctx AlertExecCtx, fromStr, toStr string) (*ExecutionResults, error) {
result := ExecutionResults{} result := ExecutionResults{}
if !c.IsValid() { if !c.IsValid() {
return nil, fmt.Errorf("Invalid conditions") return nil, fmt.Errorf("invalid conditions")
} }
request := &tsdb.TsdbQuery{ request := &tsdb.TsdbQuery{
...@@ -212,7 +212,7 @@ func (c *Condition) Execute(ctx AlertExecCtx, fromStr, toStr string) (*Execution ...@@ -212,7 +212,7 @@ func (c *Condition) Execute(ctx AlertExecCtx, fromStr, toStr string) (*Execution
conditionResult := resp.Results[c.RefID] conditionResult := resp.Results[c.RefID]
if conditionResult == nil { if conditionResult == nil {
err = fmt.Errorf("No GEL results") err = fmt.Errorf("no GEL results")
result.Error = err result.Error = err
return &result, err return &result, err
} }
...@@ -234,24 +234,24 @@ func EvaluateExecutionResult(results *ExecutionResults) (Results, error) { ...@@ -234,24 +234,24 @@ func EvaluateExecutionResult(results *ExecutionResults) (Results, error) {
for _, f := range results.Results { for _, f := range results.Results {
rowLen, err := f.RowLen() rowLen, err := f.RowLen()
if err != nil { if err != nil {
return nil, fmt.Errorf("Unable to get frame row length") return nil, fmt.Errorf("unable to get frame row length")
} }
if rowLen > 1 { if rowLen > 1 {
return nil, fmt.Errorf("Invalid frame %v: row length %v", f.Name, rowLen) return nil, fmt.Errorf("invalid frame %v: row length %v", f.Name, rowLen)
} }
if len(f.Fields) > 1 { if len(f.Fields) > 1 {
return nil, fmt.Errorf("Invalid frame %v: field length %v", f.Name, len(f.Fields)) return nil, fmt.Errorf("invalid frame %v: field length %v", f.Name, len(f.Fields))
} }
if f.Fields[0].Type() != data.FieldTypeNullableFloat64 { if f.Fields[0].Type() != data.FieldTypeNullableFloat64 {
return nil, fmt.Errorf("Invalid frame %v: field type %v", f.Name, f.Fields[0].Type()) return nil, fmt.Errorf("invalid frame %v: field type %v", f.Name, f.Fields[0].Type())
} }
labelsStr := f.Fields[0].Labels.String() labelsStr := f.Fields[0].Labels.String()
_, ok := labels[labelsStr] _, ok := labels[labelsStr]
if ok { if ok {
return nil, fmt.Errorf("Invalid frame %v: frames cannot uniquely be identified by its labels: %q", f.Name, labelsStr) return nil, fmt.Errorf("invalid frame %v: frames cannot uniquely be identified by its labels: %q", f.Name, labelsStr)
} }
labels[labelsStr] = true labels[labelsStr] = true
......
...@@ -105,7 +105,7 @@ func (ns *NotificationService) createDialer() (*gomail.Dialer, error) { ...@@ -105,7 +105,7 @@ func (ns *NotificationService) createDialer() (*gomail.Dialer, error) {
if ns.Cfg.Smtp.CertFile != "" { if ns.Cfg.Smtp.CertFile != "" {
cert, err := tls.LoadX509KeyPair(ns.Cfg.Smtp.CertFile, ns.Cfg.Smtp.KeyFile) cert, err := tls.LoadX509KeyPair(ns.Cfg.Smtp.CertFile, ns.Cfg.Smtp.KeyFile)
if err != nil { if err != nil {
return nil, fmt.Errorf("Could not load cert or key file. error: %v", err) return nil, fmt.Errorf("could not load cert or key file: %w", err)
} }
tlsconfig.Certificates = []tls.Certificate{cert} tlsconfig.Certificates = []tls.Certificate{cert}
} }
...@@ -159,7 +159,7 @@ func (ns *NotificationService) buildEmailMessage(cmd *models.SendEmailCommand) ( ...@@ -159,7 +159,7 @@ func (ns *NotificationService) buildEmailMessage(cmd *models.SendEmailCommand) (
subjectText, hasSubject := subjectData["value"] subjectText, hasSubject := subjectData["value"]
if !hasSubject { if !hasSubject {
return nil, fmt.Errorf("Missing subject in Template %s", cmd.Template) return nil, fmt.Errorf("missing subject in template %s", cmd.Template)
} }
subjectTmpl, err := template.New("subject").Parse(subjectText.(string)) subjectTmpl, err := template.New("subject").Parse(subjectText.(string))
......
...@@ -63,7 +63,7 @@ func (ns *NotificationService) Init() error { ...@@ -63,7 +63,7 @@ func (ns *NotificationService) Init() error {
} }
if !util.IsEmail(ns.Cfg.Smtp.FromAddress) { if !util.IsEmail(ns.Cfg.Smtp.FromAddress) {
return errors.New("Invalid email address for SMTP from_address config") return errors.New("invalid email address for SMTP from_address config")
} }
if setting.EmailCodeValidMinutes == 0 { if setting.EmailCodeValidMinutes == 0 {
......
...@@ -20,7 +20,7 @@ import ( ...@@ -20,7 +20,7 @@ import (
var ( var (
// ErrFolderNameMissing is returned when folder name is missing. // ErrFolderNameMissing is returned when folder name is missing.
ErrFolderNameMissing = errors.New("Folder name missing") ErrFolderNameMissing = errors.New("folder name missing")
) )
// FileReader is responsible for reading dashboards from disc and // FileReader is responsible for reading dashboards from disc and
...@@ -41,7 +41,7 @@ func NewDashboardFileReader(cfg *config, log log.Logger) (*FileReader, error) { ...@@ -41,7 +41,7 @@ func NewDashboardFileReader(cfg *config, log log.Logger) (*FileReader, error) {
if !ok { if !ok {
path, ok = cfg.Options["folder"].(string) path, ok = cfg.Options["folder"].(string)
if !ok { if !ok {
return nil, fmt.Errorf("Failed to load dashboards. path param is not a string") return nil, fmt.Errorf("failed to load dashboards, path param is not a string")
} }
log.Warn("[Deprecated] The folder property is deprecated. Please use path instead.") log.Warn("[Deprecated] The folder property is deprecated. Please use path instead.")
......
...@@ -314,7 +314,7 @@ func TestNotificationAsConfig(t *testing.T) { ...@@ -314,7 +314,7 @@ func TestNotificationAsConfig(t *testing.T) {
cfgProvider := &configReader{log: log.New("test logger")} cfgProvider := &configReader{log: log.New("test logger")}
_, err := cfgProvider.readConfig(unknownNotifier) _, err := cfgProvider.readConfig(unknownNotifier)
So(err, ShouldNotBeNil) So(err, ShouldNotBeNil)
So(err.Error(), ShouldEqual, "Unsupported notification type") So(err.Error(), ShouldEqual, `unsupported notification type "nonexisting"`)
}) })
Convey("Read incorrect properties", func() { Convey("Read incorrect properties", func() {
......
...@@ -72,7 +72,7 @@ func (rs *RenderingService) renderViaHttp(ctx context.Context, renderKey string, ...@@ -72,7 +72,7 @@ func (rs *RenderingService) renderViaHttp(ctx context.Context, renderKey string,
resp, err := netClient.Do(req) resp, err := netClient.Do(req)
if err != nil { if err != nil {
rs.log.Error("Failed to send request to remote rendering service.", "error", err) rs.log.Error("Failed to send request to remote rendering service.", "error", err)
return nil, fmt.Errorf("Failed to send request to remote rendering service. %s", err) return nil, fmt.Errorf("failed to send request to remote rendering service: %w", err)
} }
// save response to file // save response to file
...@@ -87,7 +87,8 @@ func (rs *RenderingService) renderViaHttp(ctx context.Context, renderKey string, ...@@ -87,7 +87,8 @@ func (rs *RenderingService) renderViaHttp(ctx context.Context, renderKey string,
// if we didn't get a 200 response, something went wrong. // if we didn't get a 200 response, something went wrong.
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
rs.log.Error("Remote rendering request failed", "error", resp.Status) rs.log.Error("Remote rendering request failed", "error", resp.Status)
return nil, fmt.Errorf("Remote rendering request failed. %d: %s", resp.StatusCode, resp.Status) return nil, fmt.Errorf("remote rendering request failed, status code: %d, status: %s", resp.StatusCode,
resp.Status)
} }
out, err := os.Create(filePath) out, err := os.Create(filePath)
...@@ -103,7 +104,7 @@ func (rs *RenderingService) renderViaHttp(ctx context.Context, renderKey string, ...@@ -103,7 +104,7 @@ func (rs *RenderingService) renderViaHttp(ctx context.Context, renderKey string,
return nil, ErrTimeout return nil, ErrTimeout
} }
rs.log.Error("Remote rendering request failed", "error", err) rs.log.Error("Remote rendering request failed", "error", err)
return nil, fmt.Errorf("Remote rendering request failed. %s", err) return nil, fmt.Errorf("remote rendering request failed: %w", err)
} }
return &RenderResult{FilePath: filePath}, err return &RenderResult{FilePath: filePath}, err
......
...@@ -8,8 +8,8 @@ import ( ...@@ -8,8 +8,8 @@ import (
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
) )
var ErrTimeout = errors.New("Timeout error. You can set timeout in seconds with &timeout url parameter") var ErrTimeout = errors.New("timeout error - you can set timeout in seconds with &timeout url parameter")
var ErrNoRenderer = errors.New("No renderer plugin found nor is an external render server configured") var ErrNoRenderer = errors.New("no renderer plugin found nor is an external render server configured")
var ErrPhantomJSNotInstalled = errors.New("PhantomJS executable not found") var ErrPhantomJSNotInstalled = errors.New("PhantomJS executable not found")
type Opts struct { type Opts struct {
......
...@@ -96,7 +96,7 @@ func (rs *RenderingService) renderViaPluginV2(ctx context.Context, renderKey str ...@@ -96,7 +96,7 @@ func (rs *RenderingService) renderViaPluginV2(ctx context.Context, renderKey str
return nil, err return nil, err
} }
if rsp.Error != "" { if rsp.Error != "" {
return nil, fmt.Errorf("Rendering failed: %v", rsp.Error) return nil, fmt.Errorf("rendering failed: %s", rsp.Error)
} }
return &RenderResult{FilePath: pngPath}, err return &RenderResult{FilePath: pngPath}, err
......
...@@ -286,7 +286,7 @@ func SetAlertState(cmd *models.SetAlertStateCommand) error { ...@@ -286,7 +286,7 @@ func SetAlertState(cmd *models.SetAlertStateCommand) error {
if has, err := sess.ID(cmd.AlertId).Get(&alert); err != nil { if has, err := sess.ID(cmd.AlertId).Get(&alert); err != nil {
return err return err
} else if !has { } else if !has {
return fmt.Errorf("Could not find alert") return fmt.Errorf("could not find alert")
} }
if alert.State == models.AlertStatePaused { if alert.State == models.AlertStatePaused {
......
...@@ -390,7 +390,7 @@ func UpdateAlertNotification(cmd *models.UpdateAlertNotificationCommand) error { ...@@ -390,7 +390,7 @@ func UpdateAlertNotification(cmd *models.UpdateAlertNotificationCommand) error {
} }
if sameNameQuery.Result != nil && sameNameQuery.Result.Id != current.Id { if sameNameQuery.Result != nil && sameNameQuery.Result.Id != current.Id {
return fmt.Errorf("Alert notification name %s already exists", cmd.Name) return fmt.Errorf("alert notification name %q already exists", cmd.Name)
} }
// delete empty keys // delete empty keys
...@@ -431,7 +431,7 @@ func UpdateAlertNotification(cmd *models.UpdateAlertNotificationCommand) error { ...@@ -431,7 +431,7 @@ func UpdateAlertNotification(cmd *models.UpdateAlertNotificationCommand) error {
if affected, err := sess.ID(cmd.Id).Update(current); err != nil { if affected, err := sess.ID(cmd.Id).Update(current); err != nil {
return err return err
} else if affected == 0 { } else if affected == 0 {
return fmt.Errorf("Could not update alert notification") return fmt.Errorf("could not update alert notification")
} }
cmd.Result = &current cmd.Result = &current
...@@ -578,7 +578,7 @@ func GetOrCreateAlertNotificationState(ctx context.Context, cmd *models.GetOrCre ...@@ -578,7 +578,7 @@ func GetOrCreateAlertNotificationState(ctx context.Context, cmd *models.GetOrCre
} }
if !exist { if !exist {
return errors.New("Should not happen") return errors.New("should not happen")
} }
cmd.Result = nj cmd.Result = nj
......
...@@ -15,7 +15,7 @@ import ( ...@@ -15,7 +15,7 @@ import (
func validateTimeRange(item *annotations.Item) error { func validateTimeRange(item *annotations.Item) error {
if item.EpochEnd == 0 { if item.EpochEnd == 0 {
if item.Epoch == 0 { if item.Epoch == 0 {
return errors.New("Missing Time Range") return errors.New("missing time range")
} }
item.EpochEnd = item.Epoch item.EpochEnd = item.Epoch
} }
...@@ -78,7 +78,7 @@ func (r *SqlAnnotationRepo) Update(item *annotations.Item) error { ...@@ -78,7 +78,7 @@ func (r *SqlAnnotationRepo) Update(item *annotations.Item) error {
return err return err
} }
if !isExist { if !isExist {
return errors.New("Annotation not found") return errors.New("annotation not found")
} }
existing.Updated = timeNow().UnixNano() / int64(time.Millisecond) existing.Updated = timeNow().UnixNano() / int64(time.Millisecond)
......
...@@ -39,12 +39,10 @@ func DeleteOldLoginAttempts(cmd *models.DeleteOldLoginAttemptsCommand) error { ...@@ -39,12 +39,10 @@ func DeleteOldLoginAttempts(cmd *models.DeleteOldLoginAttemptsCommand) error {
var maxId int64 var maxId int64
sql := "SELECT max(id) as id FROM login_attempt WHERE created < ?" sql := "SELECT max(id) as id FROM login_attempt WHERE created < ?"
result, err := sess.Query(sql, cmd.OlderThan.Unix()) result, err := sess.Query(sql, cmd.OlderThan.Unix())
if err != nil { if err != nil {
return err return err
} }
// nolint: gosimple if len(result) == 0 || result[0] == nil {
if result == nil || len(result) == 0 || result[0] == nil {
return nil return nil
} }
......
...@@ -116,7 +116,7 @@ func (ss *SqlStore) ensureMainOrgAndAdminUser() error { ...@@ -116,7 +116,7 @@ func (ss *SqlStore) ensureMainOrgAndAdminUser() error {
systemUserCountQuery := models.GetSystemUserCountStatsQuery{} systemUserCountQuery := models.GetSystemUserCountStatsQuery{}
err := bus.DispatchCtx(ctx, &systemUserCountQuery) err := bus.DispatchCtx(ctx, &systemUserCountQuery)
if err != nil { if err != nil {
return fmt.Errorf("Could not determine if admin user exists: %v", err) return fmt.Errorf("could not determine if admin user exists: %w", err)
} }
if systemUserCountQuery.Result.Count > 0 { if systemUserCountQuery.Result.Count > 0 {
...@@ -132,7 +132,7 @@ func (ss *SqlStore) ensureMainOrgAndAdminUser() error { ...@@ -132,7 +132,7 @@ func (ss *SqlStore) ensureMainOrgAndAdminUser() error {
cmd.IsAdmin = true cmd.IsAdmin = true
if err := bus.DispatchCtx(ctx, &cmd); err != nil { if err := bus.DispatchCtx(ctx, &cmd); err != nil {
return fmt.Errorf("Failed to create admin user: %v", err) return fmt.Errorf("failed to create admin user: %s", err)
} }
ss.log.Info("Created default admin", "user", setting.AdminUser) ss.log.Info("Created default admin", "user", setting.AdminUser)
...@@ -226,7 +226,7 @@ func (ss *SqlStore) buildConnectionString() (string, error) { ...@@ -226,7 +226,7 @@ func (ss *SqlStore) buildConnectionString() (string, error) {
cnnstr = fmt.Sprintf("file:%s?cache=%s&mode=rwc", ss.dbCfg.Path, ss.dbCfg.CacheMode) cnnstr = fmt.Sprintf("file:%s?cache=%s&mode=rwc", ss.dbCfg.Path, ss.dbCfg.CacheMode)
cnnstr += ss.buildExtraConnectionString('&') cnnstr += ss.buildExtraConnectionString('&')
default: default:
return "", fmt.Errorf("Unknown database type: %s", ss.dbCfg.Type) return "", fmt.Errorf("unknown database type: %s", ss.dbCfg.Type)
} }
return cnnstr, nil return cnnstr, nil
......
...@@ -15,7 +15,7 @@ func makeCert(config DatabaseConfig) (*tls.Config, error) { ...@@ -15,7 +15,7 @@ func makeCert(config DatabaseConfig) (*tls.Config, error) {
rootCertPool := x509.NewCertPool() rootCertPool := x509.NewCertPool()
pem, err := ioutil.ReadFile(config.CaCertPath) pem, err := ioutil.ReadFile(config.CaCertPath)
if err != nil { if err != nil {
return nil, fmt.Errorf("Could not read DB CA Cert path: %v", config.CaCertPath) return nil, fmt.Errorf("could not read DB CA Cert path %q: %w", config.CaCertPath, err)
} }
if ok := rootCertPool.AppendCertsFromPEM(pem); !ok { if ok := rootCertPool.AppendCertsFromPEM(pem); !ok {
return nil, err return nil, err
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment