Chore: Fix issues reported by staticcheck; enable stylecheck linter (#28866)

* Chore: Fix issues reported by staticcheck

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

* Apply suggestions from code review

Co-authored-by: Emil Tullstedt <emil.tullstedt@grafana.com>
This commit is contained in:
Arve Knudsen
2020-11-05 15:37:11 +01:00
committed by GitHub
co-authored by Emil Tullstedt
parent 135b83e17f
commit 676d393ec9
27 changed files with 193 additions and 182 deletions
+8 -8
View File
@@ -25,14 +25,14 @@ type UsageStatsQuerier interface {
// QueryUsageStats returns usage stats about alert rules
// configured in Grafana.
func (ae *AlertEngine) QueryUsageStats() (*UsageStats, error) {
func (e *AlertEngine) QueryUsageStats() (*UsageStats, error) {
cmd := &models.GetAllAlertsQuery{}
err := ae.Bus.Dispatch(cmd)
err := e.Bus.Dispatch(cmd)
if err != nil {
return nil, err
}
dsUsage, err := ae.mapRulesToUsageStats(cmd.Result)
dsUsage, err := e.mapRulesToUsageStats(cmd.Result)
if err != nil {
return nil, err
}
@@ -42,13 +42,13 @@ func (ae *AlertEngine) QueryUsageStats() (*UsageStats, error) {
}, nil
}
func (ae *AlertEngine) mapRulesToUsageStats(rules []*models.Alert) (DatasourceAlertUsage, error) {
func (e *AlertEngine) mapRulesToUsageStats(rules []*models.Alert) (DatasourceAlertUsage, error) {
// map of datasourceId type and frequency
typeCount := map[int64]int{}
for _, a := range rules {
dss, err := ae.parseAlertRuleModel(a.Settings)
dss, err := e.parseAlertRuleModel(a.Settings)
if err != nil {
ae.log.Debug("could not parse settings for alert rule", "id", a.Id)
e.log.Debug("could not parse settings for alert rule", "id", a.Id)
continue
}
@@ -62,7 +62,7 @@ func (ae *AlertEngine) mapRulesToUsageStats(rules []*models.Alert) (DatasourceAl
result := map[string]int{}
for k, v := range typeCount {
query := &models.GetDataSourceByIdQuery{Id: k}
err := ae.Bus.Dispatch(query)
err := e.Bus.Dispatch(query)
if err != nil {
return map[string]int{}, nil
}
@@ -74,7 +74,7 @@ func (ae *AlertEngine) mapRulesToUsageStats(rules []*models.Alert) (DatasourceAl
return result, nil
}
func (ae *AlertEngine) parseAlertRuleModel(settings json.Marshaler) ([]int64, error) {
func (e *AlertEngine) parseAlertRuleModel(settings json.Marshaler) ([]int64, error) {
datasourceIDs := []int64{}
model := alertJSONModel{}
+16 -16
View File
@@ -7,31 +7,31 @@ import (
"github.com/grafana/grafana/pkg/services/sqlstore"
)
func (srv *UserAuthTokenService) Run(ctx context.Context) error {
func (s *UserAuthTokenService) Run(ctx context.Context) error {
var err error
ticker := time.NewTicker(time.Hour)
maxInactiveLifetime := srv.Cfg.LoginMaxInactiveLifetime
maxLifetime := srv.Cfg.LoginMaxLifetime
maxInactiveLifetime := s.Cfg.LoginMaxInactiveLifetime
maxLifetime := s.Cfg.LoginMaxLifetime
err = srv.ServerLockService.LockAndExecute(ctx, "cleanup expired auth tokens", time.Hour*12, func() {
if _, err := srv.deleteExpiredTokens(ctx, maxInactiveLifetime, maxLifetime); err != nil {
srv.log.Error("An error occurred while deleting expired tokens", "err", err)
err = s.ServerLockService.LockAndExecute(ctx, "cleanup expired auth tokens", time.Hour*12, func() {
if _, err := s.deleteExpiredTokens(ctx, maxInactiveLifetime, maxLifetime); err != nil {
s.log.Error("An error occurred while deleting expired tokens", "err", err)
}
})
if err != nil {
srv.log.Error("failed to lock and execute cleanup of expired auth token", "error", err)
s.log.Error("failed to lock and execute cleanup of expired auth token", "error", err)
}
for {
select {
case <-ticker.C:
err = srv.ServerLockService.LockAndExecute(ctx, "cleanup expired auth tokens", time.Hour*12, func() {
if _, err := srv.deleteExpiredTokens(ctx, maxInactiveLifetime, maxLifetime); err != nil {
srv.log.Error("An error occurred while deleting expired tokens", "err", err)
err = s.ServerLockService.LockAndExecute(ctx, "cleanup expired auth tokens", time.Hour*12, func() {
if _, err := s.deleteExpiredTokens(ctx, maxInactiveLifetime, maxLifetime); err != nil {
s.log.Error("An error occurred while deleting expired tokens", "err", err)
}
})
if err != nil {
srv.log.Error("failed to lock and execute cleanup of expired auth token", "error", err)
s.log.Error("failed to lock and execute cleanup of expired auth token", "error", err)
}
case <-ctx.Done():
@@ -40,14 +40,14 @@ func (srv *UserAuthTokenService) Run(ctx context.Context) error {
}
}
func (srv *UserAuthTokenService) deleteExpiredTokens(ctx context.Context, maxInactiveLifetime, maxLifetime time.Duration) (int64, error) {
func (s *UserAuthTokenService) deleteExpiredTokens(ctx context.Context, maxInactiveLifetime, maxLifetime time.Duration) (int64, error) {
createdBefore := getTime().Add(-maxLifetime)
rotatedBefore := getTime().Add(-maxInactiveLifetime)
srv.log.Debug("starting cleanup of expired auth tokens", "createdBefore", createdBefore, "rotatedBefore", rotatedBefore)
s.log.Debug("starting cleanup of expired auth tokens", "createdBefore", createdBefore, "rotatedBefore", rotatedBefore)
var affected int64
err := srv.SQLStore.WithDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
err := s.SQLStore.WithDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
sql := `DELETE from user_auth_token WHERE created_at <= ? OR rotated_at <= ?`
res, err := dbSession.Exec(sql, createdBefore.Unix(), rotatedBefore.Unix())
if err != nil {
@@ -56,11 +56,11 @@ func (srv *UserAuthTokenService) deleteExpiredTokens(ctx context.Context, maxIna
affected, err = res.RowsAffected()
if err != nil {
srv.log.Error("failed to cleanup expired auth tokens", "error", err)
s.log.Error("failed to cleanup expired auth tokens", "error", err)
return nil
}
srv.log.Debug("cleanup of expired auth tokens done", "count", affected)
s.log.Debug("cleanup of expired auth tokens done", "count", affected)
return nil
})
+10 -10
View File
@@ -147,24 +147,24 @@ const (
VIEWER_ACCESS = CAN_VIEW
)
func (flag permissionFlags) canAdmin() bool {
return flag&CAN_ADMIN != 0
func (f permissionFlags) canAdmin() bool {
return f&CAN_ADMIN != 0
}
func (flag permissionFlags) canEdit() bool {
return flag&CAN_EDIT != 0
func (f permissionFlags) canEdit() bool {
return f&CAN_EDIT != 0
}
func (flag permissionFlags) canSave() bool {
return flag&CAN_SAVE != 0
func (f permissionFlags) canSave() bool {
return f&CAN_SAVE != 0
}
func (flag permissionFlags) canView() bool {
return flag&CAN_VIEW != 0
func (f permissionFlags) canView() bool {
return f&CAN_VIEW != 0
}
func (flag permissionFlags) noAccess() bool {
return flag&(CAN_ADMIN|CAN_EDIT|CAN_SAVE|CAN_VIEW) == 0
func (f permissionFlags) noAccess() bool {
return f&(CAN_ADMIN|CAN_EDIT|CAN_SAVE|CAN_VIEW) == 0
}
func (f permissionFlags) String() string {
@@ -1,7 +1,6 @@
package migrations
import (
"github.com/grafana/grafana/pkg/services/sqlstore/migrator"
. "github.com/grafana/grafana/pkg/services/sqlstore/migrator"
)
@@ -17,12 +16,12 @@ func addShortURLMigrations(mg *Migrator) {
{Name: "created_at", Type: DB_Int, Nullable: false},
{Name: "last_seen_at", Type: DB_Int, Nullable: true},
},
Indices: []*migrator.Index{
{Cols: []string{"org_id", "uid"}, Type: migrator.UniqueIndex},
Indices: []*Index{
{Cols: []string{"org_id", "uid"}, Type: UniqueIndex},
},
}
mg.AddMigration("create short_url table v1", NewAddTableMigration(shortURLV1))
mg.AddMigration("add index short_url.org_id-uid", migrator.NewAddIndexMigration(shortURLV1, shortURLV1.Indices[0]))
mg.AddMigration("add index short_url.org_id-uid", NewAddIndexMigration(shortURLV1, shortURLV1.Indices[0]))
}
+40 -40
View File
@@ -79,8 +79,8 @@ type BaseDialect struct {
driverName string
}
func (d *BaseDialect) DriverName() string {
return d.driverName
func (b *BaseDialect) DriverName() string {
return b.driverName
}
func (b *BaseDialect) ShowCreateNull() bool {
@@ -107,7 +107,7 @@ func (b *BaseDialect) Default(col *Column) string {
return col.Default
}
func (db *BaseDialect) DateTimeFunc(value string) string {
func (b *BaseDialect) DateTimeFunc(value string) string {
return value
}
@@ -145,12 +145,12 @@ func (b *BaseDialect) CreateTableSql(table *Table) string {
return sql
}
func (db *BaseDialect) AddColumnSql(tableName string, col *Column) string {
return fmt.Sprintf("alter table %s ADD COLUMN %s", db.dialect.Quote(tableName), col.StringNoPk(db.dialect))
func (b *BaseDialect) AddColumnSql(tableName string, col *Column) string {
return fmt.Sprintf("alter table %s ADD COLUMN %s", b.dialect.Quote(tableName), col.StringNoPk(b.dialect))
}
func (db *BaseDialect) CreateIndexSql(tableName string, index *Index) string {
quote := db.dialect.Quote
func (b *BaseDialect) CreateIndexSql(tableName string, index *Index) string {
quote := b.dialect.Quote
var unique string
if index.Type == UniqueIndex {
unique = " UNIQUE"
@@ -160,66 +160,66 @@ func (db *BaseDialect) CreateIndexSql(tableName string, index *Index) string {
quotedCols := []string{}
for _, col := range index.Cols {
quotedCols = append(quotedCols, db.dialect.Quote(col))
quotedCols = append(quotedCols, b.dialect.Quote(col))
}
return fmt.Sprintf("CREATE%s INDEX %v ON %v (%v);", unique, quote(idxName), quote(tableName), strings.Join(quotedCols, ","))
}
func (db *BaseDialect) QuoteColList(cols []string) string {
func (b *BaseDialect) QuoteColList(cols []string) string {
var sourceColsSql = ""
for _, col := range cols {
sourceColsSql += db.dialect.Quote(col)
sourceColsSql += b.dialect.Quote(col)
sourceColsSql += "\n, "
}
return strings.TrimSuffix(sourceColsSql, "\n, ")
}
func (db *BaseDialect) CopyTableData(sourceTable string, targetTable string, sourceCols []string, targetCols []string) string {
sourceColsSql := db.QuoteColList(sourceCols)
targetColsSql := db.QuoteColList(targetCols)
func (b *BaseDialect) CopyTableData(sourceTable string, targetTable string, sourceCols []string, targetCols []string) string {
sourceColsSql := b.QuoteColList(sourceCols)
targetColsSql := b.QuoteColList(targetCols)
quote := db.dialect.Quote
quote := b.dialect.Quote
return fmt.Sprintf("INSERT INTO %s (%s) SELECT %s FROM %s", quote(targetTable), targetColsSql, sourceColsSql, quote(sourceTable))
}
func (db *BaseDialect) DropTable(tableName string) string {
quote := db.dialect.Quote
func (b *BaseDialect) DropTable(tableName string) string {
quote := b.dialect.Quote
return fmt.Sprintf("DROP TABLE IF EXISTS %s", quote(tableName))
}
func (db *BaseDialect) RenameTable(oldName string, newName string) string {
quote := db.dialect.Quote
func (b *BaseDialect) RenameTable(oldName string, newName string) string {
quote := b.dialect.Quote
return fmt.Sprintf("ALTER TABLE %s RENAME TO %s", quote(oldName), quote(newName))
}
func (db *BaseDialect) ColumnCheckSql(tableName, columnName string) (string, []interface{}) {
func (b *BaseDialect) ColumnCheckSql(tableName, columnName string) (string, []interface{}) {
return "", nil
}
func (db *BaseDialect) DropIndexSql(tableName string, index *Index) string {
quote := db.dialect.Quote
func (b *BaseDialect) DropIndexSql(tableName string, index *Index) string {
quote := b.dialect.Quote
name := index.XName(tableName)
return fmt.Sprintf("DROP INDEX %v ON %s", quote(name), quote(tableName))
}
func (db *BaseDialect) UpdateTableSql(tableName string, columns []*Column) string {
func (b *BaseDialect) UpdateTableSql(tableName string, columns []*Column) string {
return "-- NOT REQUIRED"
}
func (db *BaseDialect) ColString(col *Column) string {
sql := db.dialect.Quote(col.Name) + " "
func (b *BaseDialect) ColString(col *Column) string {
sql := b.dialect.Quote(col.Name) + " "
sql += db.dialect.SqlType(col) + " "
sql += b.dialect.SqlType(col) + " "
if col.IsPrimaryKey {
sql += "PRIMARY KEY "
if col.IsAutoIncrement {
sql += db.dialect.AutoIncrStr() + " "
sql += b.dialect.AutoIncrStr() + " "
}
}
if db.dialect.ShowCreateNull() {
if b.dialect.ShowCreateNull() {
if col.Nullable {
sql += "NULL "
} else {
@@ -228,18 +228,18 @@ func (db *BaseDialect) ColString(col *Column) string {
}
if col.Default != "" {
sql += "DEFAULT " + db.dialect.Default(col) + " "
sql += "DEFAULT " + b.dialect.Default(col) + " "
}
return sql
}
func (db *BaseDialect) ColStringNoPk(col *Column) string {
sql := db.dialect.Quote(col.Name) + " "
func (b *BaseDialect) ColStringNoPk(col *Column) string {
sql := b.dialect.Quote(col.Name) + " "
sql += db.dialect.SqlType(col) + " "
sql += b.dialect.SqlType(col) + " "
if db.dialect.ShowCreateNull() {
if b.dialect.ShowCreateNull() {
if col.Nullable {
sql += "NULL "
} else {
@@ -248,36 +248,36 @@ func (db *BaseDialect) ColStringNoPk(col *Column) string {
}
if col.Default != "" {
sql += "DEFAULT " + db.dialect.Default(col) + " "
sql += "DEFAULT " + b.dialect.Default(col) + " "
}
return sql
}
func (db *BaseDialect) Limit(limit int64) string {
func (b *BaseDialect) Limit(limit int64) string {
return fmt.Sprintf(" LIMIT %d", limit)
}
func (db *BaseDialect) LimitOffset(limit int64, offset int64) string {
func (b *BaseDialect) LimitOffset(limit int64, offset int64) string {
return fmt.Sprintf(" LIMIT %d OFFSET %d", limit, offset)
}
func (db *BaseDialect) PreInsertId(table string, sess *xorm.Session) error {
func (b *BaseDialect) PreInsertId(table string, sess *xorm.Session) error {
return nil
}
func (db *BaseDialect) PostInsertId(table string, sess *xorm.Session) error {
func (b *BaseDialect) PostInsertId(table string, sess *xorm.Session) error {
return nil
}
func (db *BaseDialect) CleanDB() error {
func (b *BaseDialect) CleanDB() error {
return nil
}
func (db *BaseDialect) NoOpSql() string {
func (b *BaseDialect) NoOpSql() string {
return "SELECT 0;"
}
func (db *BaseDialect) TruncateDBTables() error {
func (b *BaseDialect) TruncateDBTables() error {
return nil
}
@@ -31,7 +31,7 @@ func (db *Postgres) Quote(name string) string {
return "\"" + name + "\""
}
func (b *Postgres) LikeStr() string {
func (db *Postgres) LikeStr() string {
return "ILIKE"
}
@@ -43,7 +43,7 @@ func (db *Postgres) BooleanStr(value bool) string {
return strconv.FormatBool(value)
}
func (b *Postgres) Default(col *Column) string {
func (db *Postgres) Default(col *Column) string {
if col.Type == DB_Bool {
if col.Default == "0" {
return "FALSE"