fix(test|lint): fix lint and test in go (#7346)

### Summary
 
- fix lint and test in go
This commit is contained in:
Vibhu Pandey 2025-03-18 14:01:48 +05:30 committed by GitHub
parent 5aea442939
commit 7118829107
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
29 changed files with 82 additions and 78 deletions

View File

@ -155,7 +155,7 @@ func (lm *Manager) ValidatorV3(ctx context.Context) {
tick := time.NewTicker(validationFrequency) tick := time.NewTicker(validationFrequency)
defer tick.Stop() defer tick.Stop()
lm.ValidateV3(ctx) _ = lm.ValidateV3(ctx)
for { for {
select { select {
case <-lm.done: case <-lm.done:
@ -165,7 +165,7 @@ func (lm *Manager) ValidatorV3(ctx context.Context) {
case <-lm.done: case <-lm.done:
return return
case <-tick.C: case <-tick.C:
lm.ValidateV3(ctx) _ = lm.ValidateV3(ctx)
} }
} }

View File

@ -12,7 +12,7 @@ import (
func TestBatcherWithOneAlertAndDefaultConfigs(t *testing.T) { func TestBatcherWithOneAlertAndDefaultConfigs(t *testing.T) {
batcher := New(slog.New(slog.NewTextHandler(io.Discard, nil)), NewConfig()) batcher := New(slog.New(slog.NewTextHandler(io.Discard, nil)), NewConfig())
batcher.Start(context.Background()) _ = batcher.Start(context.Background())
batcher.Add(context.Background(), &alertmanagertypes.PostableAlert{Alert: alertmanagertypes.AlertModel{ batcher.Add(context.Background(), &alertmanagertypes.PostableAlert{Alert: alertmanagertypes.AlertModel{
Labels: map[string]string{"alertname": "test"}, Labels: map[string]string{"alertname": "test"},
@ -26,7 +26,7 @@ func TestBatcherWithOneAlertAndDefaultConfigs(t *testing.T) {
func TestBatcherWithBatchSize(t *testing.T) { func TestBatcherWithBatchSize(t *testing.T) {
batcher := New(slog.New(slog.NewTextHandler(io.Discard, nil)), Config{Size: 2, Capacity: 4}) batcher := New(slog.New(slog.NewTextHandler(io.Discard, nil)), Config{Size: 2, Capacity: 4})
batcher.Start(context.Background()) _ = batcher.Start(context.Background())
var alerts alertmanagertypes.PostableAlerts var alerts alertmanagertypes.PostableAlerts
for i := 0; i < 4; i++ { for i := 0; i < 4; i++ {
@ -46,7 +46,7 @@ func TestBatcherWithBatchSize(t *testing.T) {
func TestBatcherWithCClosed(t *testing.T) { func TestBatcherWithCClosed(t *testing.T) {
batcher := New(slog.New(slog.NewTextHandler(io.Discard, nil)), Config{Size: 2, Capacity: 4}) batcher := New(slog.New(slog.NewTextHandler(io.Discard, nil)), Config{Size: 2, Capacity: 4})
batcher.Start(context.Background()) _ = batcher.Start(context.Background())
var alerts alertmanagertypes.PostableAlerts var alerts alertmanagertypes.PostableAlerts
for i := 0; i < 4; i++ { for i := 0; i < 4; i++ {

View File

@ -134,21 +134,21 @@ func New(ctx context.Context, logger *slog.Logger, registry prometheus.Registere
// Don't return here - we need to snapshot our state first. // Don't return here - we need to snapshot our state first.
} }
state, err := server.stateStore.Get(ctx, server.orgID) storableSilences, err := server.stateStore.Get(ctx, server.orgID)
if err != nil && !errors.Ast(err, errors.TypeNotFound) { if err != nil && !errors.Ast(err, errors.TypeNotFound) {
return 0, err return 0, err
} }
if state == nil { if storableSilences == nil {
state = alertmanagertypes.NewStoreableState(server.orgID) storableSilences = alertmanagertypes.NewStoreableState(server.orgID)
} }
c, err := state.Set(alertmanagertypes.SilenceStateName, server.silences) c, err := storableSilences.Set(alertmanagertypes.SilenceStateName, server.silences)
if err != nil { if err != nil {
return 0, err return 0, err
} }
return c, server.stateStore.Set(ctx, server.orgID, state) return c, server.stateStore.Set(ctx, server.orgID, storableSilences)
}) })
}() }()
@ -163,21 +163,21 @@ func New(ctx context.Context, logger *slog.Logger, registry prometheus.Registere
// Don't return without saving the current state. // Don't return without saving the current state.
} }
state, err := server.stateStore.Get(ctx, server.orgID) storableNFLog, err := server.stateStore.Get(ctx, server.orgID)
if err != nil && !errors.Ast(err, errors.TypeNotFound) { if err != nil && !errors.Ast(err, errors.TypeNotFound) {
return 0, err return 0, err
} }
if state == nil { if storableNFLog == nil {
state = alertmanagertypes.NewStoreableState(server.orgID) storableNFLog = alertmanagertypes.NewStoreableState(server.orgID)
} }
c, err := state.Set(alertmanagertypes.NFLogStateName, server.nflog) c, err := storableNFLog.Set(alertmanagertypes.NFLogStateName, server.nflog)
if err != nil { if err != nil {
return 0, err return 0, err
} }
return c, server.stateStore.Set(ctx, server.orgID, state) return c, server.stateStore.Set(ctx, server.orgID, storableNFLog)
}) })
}() }()

View File

@ -110,7 +110,6 @@ func TestServerPutAlerts(t *testing.T) {
}, },
}, },
})) }))
require.NotEmpty(t, server.alerts)
dummyRequest, err := http.NewRequest(http.MethodGet, "/alerts", nil) dummyRequest, err := http.NewRequest(http.MethodGet, "/alerts", nil)
require.NoError(t, err) require.NoError(t, err)

View File

@ -138,11 +138,15 @@ func (service *Service) TestAlert(ctx context.Context, orgID string, alert *aler
} }
func (service *Service) Stop(ctx context.Context) error { func (service *Service) Stop(ctx context.Context) error {
var errs []error
for _, server := range service.servers { for _, server := range service.servers {
server.Stop(ctx) if err := server.Stop(ctx); err != nil {
errs = append(errs, err)
service.settings.Logger().Error("failed to stop alertmanager server", "error", err)
}
} }
return nil return errors.Join(errs...)
} }
func (service *Service) newServer(ctx context.Context, orgID string) (*alertmanagerserver.Server, error) { func (service *Service) newServer(ctx context.Context, orgID string) (*alertmanagerserver.Server, error) {
@ -180,7 +184,9 @@ func (service *Service) getConfig(ctx context.Context, orgID string) (*alertmana
if err := config.SetGlobalConfig(service.config.Global); err != nil { if err := config.SetGlobalConfig(service.config.Global); err != nil {
return nil, err return nil, err
} }
config.SetRouteConfig(service.config.Route) if err := config.SetRouteConfig(service.config.Route); err != nil {
return nil, err
}
return config, nil return config, nil
} }

View File

@ -75,7 +75,7 @@ func (c *provider) SetTTL(_ context.Context, cacheKey string, ttl time.Duration)
if !found { if !found {
return return
} }
c.cc.Replace(cacheKey, item, ttl) _ = c.cc.Replace(cacheKey, item, ttl)
} }
// Remove removes the cache entry // Remove removes the cache entry

View File

@ -35,7 +35,7 @@ func TestStore(t *testing.T) {
} }
mock.ExpectSet("key", storeCacheableEntity, 10*time.Second).RedisNil() mock.ExpectSet("key", storeCacheableEntity, 10*time.Second).RedisNil()
cache.Store(context.Background(), "key", storeCacheableEntity, 10*time.Second) _ = cache.Store(context.Background(), "key", storeCacheableEntity, 10*time.Second)
if err := mock.ExpectationsWereMet(); err != nil { if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expectations: %s", err) t.Errorf("there were unfulfilled expectations: %s", err)
@ -53,7 +53,7 @@ func TestRetrieve(t *testing.T) {
retrieveCacheableEntity := new(CacheableEntity) retrieveCacheableEntity := new(CacheableEntity)
mock.ExpectSet("key", storeCacheableEntity, 10*time.Second).RedisNil() mock.ExpectSet("key", storeCacheableEntity, 10*time.Second).RedisNil()
cache.Store(context.Background(), "key", storeCacheableEntity, 10*time.Second) _ = cache.Store(context.Background(), "key", storeCacheableEntity, 10*time.Second)
data, err := storeCacheableEntity.MarshalBinary() data, err := storeCacheableEntity.MarshalBinary()
assert.NoError(t, err) assert.NoError(t, err)
@ -85,7 +85,7 @@ func TestSetTTL(t *testing.T) {
} }
mock.ExpectSet("key", storeCacheableEntity, 10*time.Second).RedisNil() mock.ExpectSet("key", storeCacheableEntity, 10*time.Second).RedisNil()
cache.Store(context.Background(), "key", storeCacheableEntity, 10*time.Second) _ = cache.Store(context.Background(), "key", storeCacheableEntity, 10*time.Second)
mock.ExpectExpire("key", 4*time.Second).RedisNil() mock.ExpectExpire("key", 4*time.Second).RedisNil()
cache.SetTTL(context.Background(), "key", 4*time.Second) cache.SetTTL(context.Background(), "key", 4*time.Second)
@ -105,7 +105,7 @@ func TestRemove(t *testing.T) {
} }
mock.ExpectSet("key", storeCacheableEntity, 10*time.Second).RedisNil() mock.ExpectSet("key", storeCacheableEntity, 10*time.Second).RedisNil()
c.Store(context.Background(), "key", storeCacheableEntity, 10*time.Second) _ = c.Store(context.Background(), "key", storeCacheableEntity, 10*time.Second)
mock.ExpectDel("key").RedisNil() mock.ExpectDel("key").RedisNil()
c.Remove(context.Background(), "key") c.Remove(context.Background(), "key")
@ -125,10 +125,10 @@ func TestBulkRemove(t *testing.T) {
} }
mock.ExpectSet("key", storeCacheableEntity, 10*time.Second).RedisNil() mock.ExpectSet("key", storeCacheableEntity, 10*time.Second).RedisNil()
c.Store(context.Background(), "key", storeCacheableEntity, 10*time.Second) _ = c.Store(context.Background(), "key", storeCacheableEntity, 10*time.Second)
mock.ExpectSet("key2", storeCacheableEntity, 10*time.Second).RedisNil() mock.ExpectSet("key2", storeCacheableEntity, 10*time.Second).RedisNil()
c.Store(context.Background(), "key2", storeCacheableEntity, 10*time.Second) _ = c.Store(context.Background(), "key2", storeCacheableEntity, 10*time.Second)
mock.ExpectDel("key", "key2").RedisNil() mock.ExpectDel("key", "key2").RedisNil()
c.BulkRemove(context.Background(), []string{"key", "key2"}) c.BulkRemove(context.Background(), []string{"key", "key2"})

View File

@ -82,7 +82,7 @@ func (a *Analytics) extractQueryRangeData(path string, r *http.Request) (map[str
} }
r.Body.Close() // must close r.Body.Close() // must close
r.Body = io.NopCloser(bytes.NewBuffer(bodyBytes)) r.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
json.Unmarshal(bodyBytes, &postData) _ = json.Unmarshal(bodyBytes, &postData)
} else { } else {
return nil, false return nil, false

View File

@ -166,8 +166,8 @@ func (r *Repo) insertConfig(
defer func() { defer func() {
if fnerr != nil { if fnerr != nil {
// remove all the damage (invalid rows from db) // remove all the damage (invalid rows from db)
r.db.Exec("DELETE FROM agent_config_versions WHERE id = $1", c.ID) _, _ = r.db.Exec("DELETE FROM agent_config_versions WHERE id = $1", c.ID)
r.db.Exec("DELETE FROM agent_config_elements WHERE version_id=$1", c.ID) _, _ = r.db.Exec("DELETE FROM agent_config_elements WHERE version_id=$1", c.ID)
} }
}() }()

View File

@ -129,7 +129,7 @@ func (m *Manager) RecommendAgentConfig(currentConfYaml []byte) (
settingVersionsUsed = append(settingVersionsUsed, configId) settingVersionsUsed = append(settingVersionsUsed, configId)
m.updateDeployStatus( _ = m.updateDeployStatus(
context.Background(), context.Background(),
featureType, featureType,
configVersion, configVersion,
@ -168,7 +168,7 @@ func (m *Manager) ReportConfigDeploymentStatus(
newStatus = string(DeployFailed) newStatus = string(DeployFailed)
message = fmt.Sprintf("%s: %s", agentId, err.Error()) message = fmt.Sprintf("%s: %s", agentId, err.Error())
} }
m.updateDeployStatusByHash( _ = m.updateDeployStatusByHash(
context.Background(), featureConfId, newStatus, message, context.Background(), featureConfId, newStatus, message,
) )
} }
@ -247,7 +247,7 @@ func Redeploy(ctx context.Context, typ ElementTypeDef, version int) *model.ApiEr
return model.InternalError(fmt.Errorf("failed to deploy the config")) return model.InternalError(fmt.Errorf("failed to deploy the config"))
} }
m.updateDeployStatus(ctx, ElementTypeSamplingRules, version, string(DeployInitiated), "Deployment started", configHash, configVersion.LastConf) _ = m.updateDeployStatus(ctx, ElementTypeSamplingRules, version, string(DeployInitiated), "Deployment started", configHash, configVersion.LastConf)
case ElementTypeDropRules: case ElementTypeDropRules:
var filterConfig *filterprocessor.Config var filterConfig *filterprocessor.Config
if err := yaml.Unmarshal([]byte(configVersion.LastConf), &filterConfig); err != nil { if err := yaml.Unmarshal([]byte(configVersion.LastConf), &filterConfig); err != nil {
@ -265,7 +265,7 @@ func Redeploy(ctx context.Context, typ ElementTypeDef, version int) *model.ApiEr
return err return err
} }
m.updateDeployStatus(ctx, ElementTypeSamplingRules, version, string(DeployInitiated), "Deployment started", configHash, configVersion.LastConf) _ = m.updateDeployStatus(ctx, ElementTypeSamplingRules, version, string(DeployInitiated), "Deployment started", configHash, configVersion.LastConf)
} }
return nil return nil
@ -296,7 +296,7 @@ func UpsertFilterProcessor(ctx context.Context, version int, config *filterproce
zap.L().Warn("unexpected error while transforming processor config to yaml", zap.Error(yamlErr)) zap.L().Warn("unexpected error while transforming processor config to yaml", zap.Error(yamlErr))
} }
m.updateDeployStatus(ctx, ElementTypeDropRules, version, string(DeployInitiated), "Deployment started", configHash, string(processorConfYaml)) _ = m.updateDeployStatus(ctx, ElementTypeDropRules, version, string(DeployInitiated), "Deployment started", configHash, string(processorConfYaml))
return nil return nil
} }
@ -320,7 +320,7 @@ func (m *Manager) OnConfigUpdate(agentId string, hash string, err error) {
message = fmt.Sprintf("%s: %s", agentId, err.Error()) message = fmt.Sprintf("%s: %s", agentId, err.Error())
} }
m.updateDeployStatusByHash(context.Background(), hash, status, message) _ = m.updateDeployStatusByHash(context.Background(), hash, status, message)
} }
// UpsertSamplingProcessor updates the agent config with new filter processor params // UpsertSamplingProcessor updates the agent config with new filter processor params
@ -347,6 +347,6 @@ func UpsertSamplingProcessor(ctx context.Context, version int, config *tsp.Confi
zap.L().Warn("unexpected error while transforming processor config to yaml", zap.Error(yamlErr)) zap.L().Warn("unexpected error while transforming processor config to yaml", zap.Error(yamlErr))
} }
m.updateDeployStatus(ctx, ElementTypeSamplingRules, version, string(DeployInitiated), "Deployment started", configHash, string(processorConfYaml)) _ = m.updateDeployStatus(ctx, ElementTypeSamplingRules, version, string(DeployInitiated), "Deployment started", configHash, string(processorConfYaml))
return nil return nil
} }

View File

@ -92,7 +92,7 @@ func Enrich(params *v3.QueryRangeParamsV3, fields map[string]v3.AttributeKey) {
if query.Expression != queryName && query.DataSource != v3.DataSourceLogs { if query.Expression != queryName && query.DataSource != v3.DataSourceLogs {
continue continue
} }
EnrichLogsQuery(query, fields) _ = EnrichLogsQuery(query, fields)
} }
} }

View File

@ -80,7 +80,7 @@ func (ta *MockAgentConfigProvider) RecommendAgentConfig(baseConfYaml []byte) (
return nil, "", errors.Wrap(err, "could not unmarshal baseConf") return nil, "", errors.Wrap(err, "could not unmarshal baseConf")
} }
k.Set("extensions.zpages.endpoint", ta.ZPagesEndpoint) _ = k.Set("extensions.zpages.endpoint", ta.ZPagesEndpoint)
recommendedYaml, err := k.Marshal(yaml.Parser()) recommendedYaml, err := k.Marshal(yaml.Parser())
if err != nil { if err != nil {
return nil, "", errors.Wrap(err, "could not marshal recommended conf") return nil, "", errors.Wrap(err, "could not marshal recommended conf")

View File

@ -359,5 +359,5 @@ func (agent *Agent) SendToAgent(msg *protobufs.ServerToAgent) {
agent.connMutex.Lock() agent.connMutex.Lock()
defer agent.connMutex.Unlock() defer agent.connMutex.Unlock()
agent.conn.Send(context.Background(), msg) _ = agent.conn.Send(context.Background(), msg)
} }

View File

@ -51,7 +51,7 @@ func (agents *Agents) RemoveConnection(conn types.Connection) {
agent := agents.agentsById[instanceId] agent := agents.agentsById[instanceId]
agent.CurrentStatus = AgentStatusDisconnected agent.CurrentStatus = AgentStatusDisconnected
agent.TerminatedAt = time.Now() agent.TerminatedAt = time.Now()
agent.Upsert() _ = agent.Upsert()
delete(agents.agentsById, instanceId) delete(agents.agentsById, instanceId)
} }
delete(agents.connections, conn) delete(agents.connections, conn)

View File

@ -71,7 +71,7 @@ func (srv *Server) Stop() {
defer cleanup() defer cleanup()
} }
srv.server.Stop(context.Background()) _ = srv.server.Stop(context.Background())
} }
func (srv *Server) onDisconnect(conn types.Connection) { func (srv *Server) onDisconnect(conn types.Connection) {

View File

@ -160,7 +160,7 @@ func (cp *ConfigParser) CheckProcessorInPipeline(pipelineName, name string) bool
func (cp *ConfigParser) Merge(c *confmap.Conf) { func (cp *ConfigParser) Merge(c *confmap.Conf) {
cp.lock.Lock() cp.lock.Lock()
defer cp.lock.Unlock() defer cp.lock.Unlock()
cp.agentConf.Merge(c) _ = cp.agentConf.Merge(c)
} }
func (cp *ConfigParser) UpdateProcessors(processors map[string]interface{}) { func (cp *ConfigParser) UpdateProcessors(processors map[string]interface{}) {

View File

@ -47,7 +47,7 @@ func (c *cache) SetTTL(cacheKey string, ttl time.Duration) {
if !found { if !found {
return return
} }
c.cc.Replace(cacheKey, item, ttl) _ = c.cc.Replace(cacheKey, item, ttl)
} }
// Remove removes the cache entry // Remove removes the cache entry

View File

@ -13,7 +13,7 @@ func TestStore(t *testing.T) {
c := WithClient(db) c := WithClient(db)
mock.ExpectSet("key", []byte("value"), 10*time.Second).RedisNil() mock.ExpectSet("key", []byte("value"), 10*time.Second).RedisNil()
c.Store("key", []byte("value"), 10*time.Second) _ = c.Store("key", []byte("value"), 10*time.Second)
if err := mock.ExpectationsWereMet(); err != nil { if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expectations: %s", err) t.Errorf("there were unfulfilled expectations: %s", err)
@ -24,7 +24,7 @@ func TestRetrieve(t *testing.T) {
db, mock := redismock.NewClientMock() db, mock := redismock.NewClientMock()
c := WithClient(db) c := WithClient(db)
mock.ExpectSet("key", []byte("value"), 10*time.Second).RedisNil() mock.ExpectSet("key", []byte("value"), 10*time.Second).RedisNil()
c.Store("key", []byte("value"), 10*time.Second) _ = c.Store("key", []byte("value"), 10*time.Second)
mock.ExpectGet("key").SetVal("value") mock.ExpectGet("key").SetVal("value")
data, retrieveStatus, err := c.Retrieve("key", false) data, retrieveStatus, err := c.Retrieve("key", false)
@ -49,7 +49,7 @@ func TestSetTTL(t *testing.T) {
db, mock := redismock.NewClientMock() db, mock := redismock.NewClientMock()
c := WithClient(db) c := WithClient(db)
mock.ExpectSet("key", []byte("value"), 10*time.Second).RedisNil() mock.ExpectSet("key", []byte("value"), 10*time.Second).RedisNil()
c.Store("key", []byte("value"), 10*time.Second) _ = c.Store("key", []byte("value"), 10*time.Second)
mock.ExpectExpire("key", 4*time.Second).RedisNil() mock.ExpectExpire("key", 4*time.Second).RedisNil()
c.SetTTL("key", 4*time.Second) c.SetTTL("key", 4*time.Second)
@ -63,7 +63,7 @@ func TestRemove(t *testing.T) {
db, mock := redismock.NewClientMock() db, mock := redismock.NewClientMock()
c := WithClient(db) c := WithClient(db)
mock.ExpectSet("key", []byte("value"), 10*time.Second).RedisNil() mock.ExpectSet("key", []byte("value"), 10*time.Second).RedisNil()
c.Store("key", []byte("value"), 10*time.Second) _ = c.Store("key", []byte("value"), 10*time.Second)
mock.ExpectDel("key").RedisNil() mock.ExpectDel("key").RedisNil()
c.Remove("key") c.Remove("key")
@ -77,10 +77,10 @@ func TestBulkRemove(t *testing.T) {
db, mock := redismock.NewClientMock() db, mock := redismock.NewClientMock()
c := WithClient(db) c := WithClient(db)
mock.ExpectSet("key", []byte("value"), 10*time.Second).RedisNil() mock.ExpectSet("key", []byte("value"), 10*time.Second).RedisNil()
c.Store("key", []byte("value"), 10*time.Second) _ = c.Store("key", []byte("value"), 10*time.Second)
mock.ExpectSet("key2", []byte("value2"), 10*time.Second).RedisNil() mock.ExpectSet("key2", []byte("value2"), 10*time.Second).RedisNil()
c.Store("key2", []byte("value2"), 10*time.Second) _ = c.Store("key2", []byte("value2"), 10*time.Second)
mock.ExpectDel("key", "key2").RedisNil() mock.ExpectDel("key", "key2").RedisNil()
c.BulkRemove([]string{"key", "key2"}) c.BulkRemove([]string{"key", "key2"})

View File

@ -354,7 +354,7 @@ func (item *SearchSpanResponseItem) GetValues() []interface{} {
references := []OtelSpanRef{} references := []OtelSpanRef{}
jsonbody, _ := json.Marshal(item.References) jsonbody, _ := json.Marshal(item.References)
json.Unmarshal(jsonbody, &references) _ = json.Unmarshal(jsonbody, &references)
referencesStringArray := []string{} referencesStringArray := []string{}
for _, item := range references { for _, item := range references {
@ -750,7 +750,7 @@ type ClusterInfo struct {
func (ci *ClusterInfo) GetMapFromStruct() map[string]interface{} { func (ci *ClusterInfo) GetMapFromStruct() map[string]interface{} {
var clusterInfoMap map[string]interface{} var clusterInfoMap map[string]interface{}
data, _ := json.Marshal(*ci) data, _ := json.Marshal(*ci)
json.Unmarshal(data, &clusterInfoMap) _ = json.Unmarshal(data, &clusterInfoMap)
return clusterInfoMap return clusterInfoMap
} }

View File

@ -40,10 +40,10 @@ func FromReader(ch interfaces.Reader) (*PqlEngine, error) {
func NewPqlEngine(config *pconfig.Config) (*PqlEngine, error) { func NewPqlEngine(config *pconfig.Config) (*PqlEngine, error) {
logLevel := promlog.AllowedLevel{} logLevel := promlog.AllowedLevel{}
logLevel.Set("debug") _ = logLevel.Set("debug")
allowedFormat := promlog.AllowedFormat{} allowedFormat := promlog.AllowedFormat{}
allowedFormat.Set("logfmt") _ = allowedFormat.Set("logfmt")
promlogConfig := promlog.Config{ promlogConfig := promlog.Config{
Level: &logLevel, Level: &logLevel,
@ -80,7 +80,7 @@ func NewPqlEngine(config *pconfig.Config) (*PqlEngine, error) {
) )
fanoutStorage := pstorage.NewFanout(logger, remoteStorage) fanoutStorage := pstorage.NewFanout(logger, remoteStorage)
remoteStorage.ApplyConfig(config) _ = remoteStorage.ApplyConfig(config)
return &PqlEngine{ return &PqlEngine{
engine: e, engine: e,

View File

@ -515,8 +515,8 @@ func createTelemetry() {
nextHeartbeat := calculateNextRun(HEART_BEAT_DURATION, SCHEDULE_START_TIME) nextHeartbeat := calculateNextRun(HEART_BEAT_DURATION, SCHEDULE_START_TIME)
nextActiveUser := calculateNextRun(ACTIVE_USER_DURATION, SCHEDULE_START_TIME) nextActiveUser := calculateNextRun(ACTIVE_USER_DURATION, SCHEDULE_START_TIME)
s.Every(HEART_BEAT_DURATION).StartAt(nextHeartbeat).Do(heartbeatFunc) _, _ = s.Every(HEART_BEAT_DURATION).StartAt(nextHeartbeat).Do(heartbeatFunc)
s.Every(ACTIVE_USER_DURATION).StartAt(nextActiveUser).Do(activeUserFunc) _, _ = s.Every(ACTIVE_USER_DURATION).StartAt(nextActiveUser).Do(activeUserFunc)
} }
// Schedule immediate execution and subsequent runs // Schedule immediate execution and subsequent runs
@ -559,18 +559,18 @@ func (a *Telemetry) IdentifyUser(user *types.User) {
if a.saasOperator != nil { if a.saasOperator != nil {
if role != "" { if role != "" {
a.saasOperator.Enqueue(analytics.Identify{ _ = a.saasOperator.Enqueue(analytics.Identify{
UserId: a.userEmail, UserId: a.userEmail,
Traits: analytics.NewTraits().SetName(user.Name).SetEmail(user.Email).Set("role", role), Traits: analytics.NewTraits().SetName(user.Name).SetEmail(user.Email).Set("role", role),
}) })
} else { } else {
a.saasOperator.Enqueue(analytics.Identify{ _ = a.saasOperator.Enqueue(analytics.Identify{
UserId: a.userEmail, UserId: a.userEmail,
Traits: analytics.NewTraits().SetName(user.Name).SetEmail(user.Email), Traits: analytics.NewTraits().SetName(user.Name).SetEmail(user.Email),
}) })
} }
a.saasOperator.Enqueue(analytics.Group{ _ = a.saasOperator.Enqueue(analytics.Group{
UserId: a.userEmail, UserId: a.userEmail,
GroupId: a.getCompanyDomain(), GroupId: a.getCompanyDomain(),
Traits: analytics.NewTraits().Set("company_domain", a.getCompanyDomain()), Traits: analytics.NewTraits().Set("company_domain", a.getCompanyDomain()),
@ -578,12 +578,12 @@ func (a *Telemetry) IdentifyUser(user *types.User) {
} }
if a.ossOperator != nil { if a.ossOperator != nil {
a.ossOperator.Enqueue(analytics.Identify{ _ = a.ossOperator.Enqueue(analytics.Identify{
UserId: a.ipAddress, UserId: a.ipAddress,
Traits: analytics.NewTraits().SetName(user.Name).SetEmail(user.Email).Set("ip", a.ipAddress), Traits: analytics.NewTraits().SetName(user.Name).SetEmail(user.Email).Set("ip", a.ipAddress),
}) })
// Updating a groups properties // Updating a groups properties
a.ossOperator.Enqueue(analytics.Group{ _ = a.ossOperator.Enqueue(analytics.Group{
UserId: a.ipAddress, UserId: a.ipAddress,
GroupId: a.getCompanyDomain(), GroupId: a.getCompanyDomain(),
Traits: analytics.NewTraits().Set("company_domain", a.getCompanyDomain()), Traits: analytics.NewTraits().Set("company_domain", a.getCompanyDomain()),
@ -611,13 +611,13 @@ func (a *Telemetry) SendIdentifyEvent(data map[string]interface{}, userEmail str
traits.Set(k, v) traits.Set(k, v)
} }
if a.saasOperator != nil { if a.saasOperator != nil {
a.saasOperator.Enqueue(analytics.Identify{ _ = a.saasOperator.Enqueue(analytics.Identify{
UserId: a.GetUserEmail(), UserId: a.GetUserEmail(),
Traits: traits, Traits: traits,
}) })
} }
if a.ossOperator != nil { if a.ossOperator != nil {
a.ossOperator.Enqueue(analytics.Identify{ _ = a.ossOperator.Enqueue(analytics.Identify{
UserId: a.ipAddress, UserId: a.ipAddress,
Traits: traits, Traits: traits,
}) })
@ -644,14 +644,14 @@ func (a *Telemetry) SendGroupEvent(data map[string]interface{}, userEmail string
traits.Set(k, v) traits.Set(k, v)
} }
if a.saasOperator != nil { if a.saasOperator != nil {
a.saasOperator.Enqueue(analytics.Group{ _ = a.saasOperator.Enqueue(analytics.Group{
UserId: a.GetUserEmail(), UserId: a.GetUserEmail(),
GroupId: a.getCompanyDomain(), GroupId: a.getCompanyDomain(),
Traits: traits, Traits: traits,
}) })
} }
if a.ossOperator != nil { if a.ossOperator != nil {
a.ossOperator.Enqueue(analytics.Group{ _ = a.ossOperator.Enqueue(analytics.Group{
UserId: a.ipAddress, UserId: a.ipAddress,
GroupId: a.getCompanyDomain(), GroupId: a.getCompanyDomain(),
Traits: traits, Traits: traits,
@ -757,7 +757,7 @@ func (a *Telemetry) SendEvent(event string, data map[string]interface{}, userEma
_, isSaaSEvent := SAAS_EVENTS_LIST[event] _, isSaaSEvent := SAAS_EVENTS_LIST[event]
if a.saasOperator != nil && a.GetUserEmail() != "" && (isSaaSEvent || viaEventsAPI) { if a.saasOperator != nil && a.GetUserEmail() != "" && (isSaaSEvent || viaEventsAPI) {
a.saasOperator.Enqueue(analytics.Track{ _ = a.saasOperator.Enqueue(analytics.Track{
Event: event, Event: event,
UserId: a.GetUserEmail(), UserId: a.GetUserEmail(),
Properties: properties, Properties: properties,
@ -772,7 +772,7 @@ func (a *Telemetry) SendEvent(event string, data map[string]interface{}, userEma
_, isOSSEvent := OSS_EVENTS_LIST[event] _, isOSSEvent := OSS_EVENTS_LIST[event]
if a.ossOperator != nil && isOSSEvent { if a.ossOperator != nil && isOSSEvent {
a.ossOperator.Enqueue(analytics.Track{ _ = a.ossOperator.Enqueue(analytics.Track{
Event: event, Event: event,
UserId: userId, UserId: userId,
Properties: properties, Properties: properties,

View File

@ -70,7 +70,7 @@ func NewQueryServiceDBForTests(t *testing.T) sqlstore.SQLStore {
if err != nil { if err != nil {
t.Fatalf("could not initialize dao: %v", err) t.Fatalf("could not initialize dao: %v", err)
} }
dashboards.InitDB(sqlStore.BunDB()) _ = dashboards.InitDB(sqlStore.BunDB())
return sqlStore return sqlStore
} }

View File

@ -37,7 +37,7 @@ func (migration *modifyDatetime) Up(ctx context.Context, db *bun.DB) error {
if err != nil { if err != nil {
return err return err
} }
defer tx.Rollback() defer tx.Rollback() //nolint:errcheck
tables := []string{"dashboards", "rules", "planned_maintenance", "ttl_status", "saved_views"} tables := []string{"dashboards", "rules", "planned_maintenance", "ttl_status", "saved_views"}
columns := []string{"created_at", "updated_at"} columns := []string{"created_at", "updated_at"}

View File

@ -38,7 +38,7 @@ func (migration *modifyOrgDomain) Up(ctx context.Context, db *bun.DB) error {
if err != nil { if err != nil {
return err return err
} }
defer tx.Rollback() defer tx.Rollback() //nolint:errcheck
// rename old column // rename old column
if _, err := tx.ExecContext(ctx, `ALTER TABLE org_domains RENAME COLUMN updated_at TO updated_at_old`); err != nil { if _, err := tx.ExecContext(ctx, `ALTER TABLE org_domains RENAME COLUMN updated_at TO updated_at_old`); err != nil {

View File

@ -42,7 +42,7 @@ func (migration *updateOrganization) Up(ctx context.Context, db *bun.DB) error {
if err != nil { if err != nil {
return err return err
} }
defer tx.Rollback() defer tx.Rollback() //nolint:errcheck
// update apdex settings table // update apdex settings table
if err := updateApdexSettings(ctx, tx); err != nil { if err := updateApdexSettings(ctx, tx); err != nil {

View File

@ -41,7 +41,7 @@ func (migration *updateDashboardAndSavedViews) Up(ctx context.Context, db *bun.D
if err != nil { if err != nil {
return err return err
} }
defer tx.Rollback() defer tx.Rollback() //nolint:errcheck
// get all org ids // get all org ids
var orgIDs []string var orgIDs []string

View File

@ -84,14 +84,13 @@ func (dialect *PGDialect) MigrateIntToBoolean(ctx context.Context, bun bun.IDB,
func (dialect *PGDialect) GetColumnType(ctx context.Context, bun bun.IDB, table string, column string) (string, error) { func (dialect *PGDialect) GetColumnType(ctx context.Context, bun bun.IDB, table string, column string) (string, error) {
var columnType string var columnType string
var err error
err = bun.NewSelect(). err := bun.NewSelect().
ColumnExpr("data_type"). ColumnExpr("data_type").
TableExpr("information_schema.columns"). TableExpr("information_schema.columns").
Where("table_name = ?", table). Where("table_name = ?", table).
Where("column_name = ?", column). Where("column_name = ?", column).
Scan(ctx, &columnType) Scan(ctx, &columnType)
if err != nil { if err != nil {
return "", err return "", err
} }

View File

@ -84,14 +84,12 @@ func (dialect *SQLiteDialect) MigrateIntToBoolean(ctx context.Context, bun bun.I
func (dialect *SQLiteDialect) GetColumnType(ctx context.Context, bun bun.IDB, table string, column string) (string, error) { func (dialect *SQLiteDialect) GetColumnType(ctx context.Context, bun bun.IDB, table string, column string) (string, error) {
var columnType string var columnType string
var err error
err = bun.NewSelect(). err := bun.NewSelect().
ColumnExpr("type"). ColumnExpr("type").
TableExpr("pragma_table_info(?)", table). TableExpr("pragma_table_info(?)", table).
Where("name = ?", column). Where("name = ?", column).
Scan(ctx, &columnType) Scan(ctx, &columnType)
if err != nil { if err != nil {
return "", err return "", err
} }

View File

@ -29,6 +29,8 @@ func (s *StateStore) Set(ctx context.Context, orgID string, storeableState *aler
} }
func (s *StateStore) Get(ctx context.Context, orgID string) (*alertmanagertypes.StoreableState, error) { func (s *StateStore) Get(ctx context.Context, orgID string) (*alertmanagertypes.StoreableState, error) {
s.mtx.RLock()
defer s.mtx.RUnlock()
if _, ok := s.states[orgID]; !ok { if _, ok := s.states[orgID]; !ok {
return nil, errors.Newf(errors.TypeNotFound, alertmanagertypes.ErrCodeAlertmanagerStateNotFound, "state for orgID %q not found", orgID) return nil, errors.Newf(errors.TypeNotFound, alertmanagertypes.ErrCodeAlertmanagerStateNotFound, "state for orgID %q not found", orgID)
} }