add linter, refactor

This commit is contained in:
Maxim Merzhanov committed 2020-03-12 13:12:43 +03:00
1 parent 9d61ec49c3
commit 1fa20f9cda
24 files changed
+145 -71

No files matched your search

+39
View File
@@ -0,0 +1,39 @@
run:
tests: false
linters:
enable-all: true
disable:
- goimports
- depguard # не используется
- gochecknoinits
- gochecknoglobals
- wsl
- gocognit
- godox # находит тудушки, не нужно
- golint # подумать, может вернуть
- stylecheck # подумать, может вернуть
linters-settings:
maligned:
suggest-new: true
lll:
line-length: 140
tab-width: 1
funlen:
lines: 80
statements: 40
prealloc:
# Report preallocation suggestions only on simple loops that have no returns/breaks/continues/gotos in them.
# True by default.
simple: true
range-loops: true # Report preallocation suggestions on range loops, true by default
for-loops: true # Report preallocation suggestions on for loops, false by default
gocritic:
# Enable multiple checks by tags, run `GL_DEBUG=gocritic golangci-lint run` to see all tags and checks.
# Empty list by default. See https://github.com/go-critic/go-critic#usage -> section "Tags".
enabled-tags:
- diagnostic
- performance
disabled-checks:
- hugeParam # в данном проекте не нужен
-1
View File
@@ -148,7 +148,6 @@ func (client *Client) declareMyselfToLeader(leaderClient *SocketLeaderClient) {
} else if response != utils.WsOkResponse {
log.Warnf(codes.SendDeclarationToLeader, "send declaration to leader. response: %s", response)
}
}
// used when a leader need to declare himself to a cluster
+3 -1
View File
@@ -3,15 +3,17 @@ package cluster
import (
"bytes"
"encoding/binary"
"time"
"github.com/integration-system/isp-lib/structure"
log "github.com/integration-system/isp-log"
"isp-config-service/codes"
"isp-config-service/entity"
"time"
)
const (
ApplyCommandEvent = "CONFIG_CLUSTER:APPLY_COMMAND"
CommandSizeBytes = 8
ClusterParam = "cluster"
)
+1
View File
@@ -1,3 +1,4 @@
//nolint lll
package conf
import (
+3 -3
View File
@@ -77,11 +77,11 @@ func (c *config) CreateUpdateConfig(config domain.CreateUpdateConfigRequest) (*d
err := PerformSyncApplyWithError(command, "UpsertConfigCommand", &response)
if err != nil {
return nil, err
} else if response.Config != nil {
return response.Config, nil
} else {
} else if response.ErrorDetails != nil {
return nil, utils.CreateValidationErrorDetails(codes.InvalidArgument, utils.ValidationError, response.ErrorDetails)
}
return response.Config, nil
}
// MarkConfigAsActive godoc
+5 -1
View File
@@ -1,13 +1,15 @@
package entity
import (
"github.com/integration-system/isp-lib/config/schema"
"time"
"github.com/integration-system/isp-lib/config/schema"
)
type ConfigData map[string]interface{}
type Config struct {
//nolint
tableName string `sql:"?db_schema.configs" json:"-"`
Id string `json:"id"`
Name string `json:"name" valid:"required~Required"`
@@ -22,6 +24,7 @@ type Config struct {
}
type CommonConfig struct {
//nolint
tableName string `sql:"?db_schema.common_configs" json:"-"`
Id string `json:"id"`
Name string `json:"name" valid:"required~Required"`
@@ -32,6 +35,7 @@ type CommonConfig struct {
}
type ConfigSchema struct {
//nolint
tableName string `sql:"?db_schema.config_schemas" json:"-"`
Id string `json:"id"`
Version string
+1
View File
@@ -3,6 +3,7 @@ package entity
import "time"
type Module struct {
//nolint
tableName string `sql:"?db_schema.modules" json:"-"`
Id string `json:"id"`
Name string `json:"name" valid:"required~Required"`
+1
View File
@@ -1,3 +1,4 @@
//nolint lll
package helper
import (
+3 -1
View File
@@ -83,6 +83,7 @@ func main() {
connectionReadLimit := defaultWsConnectionReadLimit
if cfg.WS.WsConnectionReadLimitKB > 0 {
//nolint gomnd
connectionReadLimit = cfg.WS.WsConnectionReadLimitKB << 10
}
cluster.WsConnectionReadLimit = connectionReadLimit
@@ -147,7 +148,8 @@ func initWebsocket(ctx context.Context, connectionReadLimit int64, listener net.
holder.HTTPServer = httpServer
}
func initRaft(listener net.Listener, clusterCfg conf.ClusterConfiguration, declaration structure.BackendDeclaration) (*cluster.Client, *store.Store) {
func initRaft(listener net.Listener, clusterCfg conf.ClusterConfiguration,
declaration structure.BackendDeclaration) (*cluster.Client, *store.Store) {
raftState, err := store.NewStateFromRepository()
if err != nil {
log.Fatal(codes.RestoreFromRepositoryError, err)
+1
View File
@@ -1,3 +1,4 @@
//nolint dupl
package model
import (
+1
View File
@@ -1,3 +1,4 @@
//nolint dupl
package model
import (
+1
View File
@@ -1,3 +1,4 @@
//nolint dupl
package model
import (
+1
View File
@@ -1,3 +1,4 @@
//nolint dupl
package model
import (
+1
View File
@@ -21,6 +21,7 @@ func (l *LoggerAdapter) Log(level logrus.Level, msg string, args ...interface{})
msg = fmt.Sprintf("%s: %s", l.name, msg)
}
if len(args) != 0 {
//nolint gomnd
metadata := make(map[string]interface{}, len(args)/2)
for i := 0; i < len(args)-1; i += 2 {
k := cast.ToString(args[i])
+9 -7
View File
@@ -1,19 +1,21 @@
package raft
import (
"github.com/hashicorp/raft"
raftboltdb "github.com/hashicorp/raft-boltdb"
"github.com/pkg/errors"
"isp-config-service/conf"
"net"
"os"
"path/filepath"
"time"
"github.com/hashicorp/raft"
raftboltdb "github.com/hashicorp/raft-boltdb"
"github.com/pkg/errors"
"isp-config-service/conf"
)
const (
defaultSyncTimeout = 3 * time.Second
dbFile = "raft_db"
defaultSyncTimeout = 3 * time.Second
leaderNotificationChBuffer = 10
dbFile = "raft_db"
)
type ChangeLeaderNotification struct {
@@ -120,7 +122,7 @@ func NewRaft(tcpListener net.Listener, configuration conf.ClusterConfiguration,
cfg: configuration,
leaderObs: leaderObs,
leaderObsCh: leaderObsCh,
changeLeaderCh: make(chan ChangeLeaderNotification, 10),
changeLeaderCh: make(chan ChangeLeaderNotification, leaderNotificationChBuffer),
closer: make(chan struct{}),
}
go raft.listenLeader()
+12 -11
View File
@@ -17,7 +17,8 @@ var (
type commonConfigService struct{}
func (s commonConfigService) HandleDeleteConfigsCommand(deleteCommonConfig cluster.DeleteCommonConfig, state state.WritableState) cluster.ResponseWithError {
func (s commonConfigService) HandleDeleteConfigsCommand(
deleteCommonConfig cluster.DeleteCommonConfig, state state.WritableState) cluster.ResponseWithError {
links := s.GetCommonConfigLinks(deleteCommonConfig.Id, state)
if len(links) > 0 {
return cluster.NewResponse(domain.DeleteCommonConfigResponse{Deleted: false, Links: links})
@@ -36,12 +37,14 @@ func (s commonConfigService) HandleDeleteConfigsCommand(deleteCommonConfig clust
return cluster.NewResponse(domain.DeleteCommonConfigResponse{Deleted: deleted > 0})
}
func (s commonConfigService) HandleUpsertConfigCommand(upsertConfig cluster.UpsertCommonConfig, state state.WritableState) cluster.ResponseWithError {
func (s commonConfigService) HandleUpsertConfigCommand(
upsertConfig cluster.UpsertCommonConfig, state state.WritableState) cluster.ResponseWithError {
config := upsertConfig.Config
configsByName := state.CommonConfigs().GetByName(config.Name)
if upsertConfig.Create {
if len(configsByName) > 0 {
return cluster.NewResponseErrorf(codes2.AlreadyExists, "common config with name %s already exists", upsertConfig.Config.Name)
return cluster.NewResponseErrorf(codes2.AlreadyExists,
"common config with name %s already exists", upsertConfig.Config.Name)
}
config = state.WritableCommonConfigs().Create(config)
} else {
@@ -51,7 +54,8 @@ func (s commonConfigService) HandleUpsertConfigCommand(upsertConfig cluster.Upse
return cluster.NewResponseErrorf(codes2.NotFound, "common config with id %s not found", config.Id)
}
if len(configsByName) > 0 && configs[0].Id != configsByName[0].Id {
return cluster.NewResponseErrorf(codes2.AlreadyExists, "common config with name %s already exists", upsertConfig.Config.Name)
return cluster.NewResponseErrorf(codes2.AlreadyExists,
"common config with name %s already exists", upsertConfig.Config.Name)
}
config.CreatedAt = configs[0].CreatedAt
state.WritableCommonConfigs().UpdateById(config)
@@ -76,15 +80,12 @@ func (s commonConfigService) HandleUpsertConfigCommand(upsertConfig cluster.Upse
func (s commonConfigService) GetCommonConfigLinks(commonConfigID string, state state.ReadonlyState) domain.CommonConfigLinks {
configs := state.Configs().FilterByCommonConfigs([]string{commonConfigID})
result := make(domain.CommonConfigLinks)
for _, c := range configs {
module := state.Modules().GetById(c.ModuleId)
for i := range configs {
module := state.Modules().GetById(configs[i].ModuleId)
if module != nil {
if configs, ok := result[module.Name]; ok {
result[module.Name] = append(configs, c.Name)
} else {
result[module.Name] = []string{c.Name}
}
result[module.Name] = append(result[module.Name], configs[i].Name)
}
}
return result
}
+18 -13
View File
@@ -3,6 +3,7 @@ package service
import (
"encoding/json"
"fmt"
"github.com/integration-system/bellows"
"github.com/integration-system/isp-lib/utils"
log "github.com/integration-system/isp-log"
@@ -51,7 +52,8 @@ func (cs configService) GetCompiledConfig(moduleName string, state state.Readonl
return cs.CompileConfig(config.Data, state, config.CommonConfigs...), nil
}
func (configService) CompileConfig(data map[string]interface{}, state state.ReadonlyState, commonConfigsIds ...string) map[string]interface{} {
func (configService) CompileConfig(
data map[string]interface{}, state state.ReadonlyState, commonConfigsIds ...string) map[string]interface{} {
commonConfigs := state.CommonConfigs().GetByIds(commonConfigsIds)
configsToMerge := make([]map[string]interface{}, 0, len(commonConfigs))
for _, common := range commonConfigs {
@@ -62,7 +64,8 @@ func (configService) CompileConfig(data map[string]interface{}, state state.Read
return mergeNestedMaps(configsToMerge...)
}
func (configService) HandleActivateConfigCommand(activateConfig cluster.ActivateConfig, state state.WritableState) cluster.ResponseWithError {
func (configService) HandleActivateConfigCommand(
activateConfig cluster.ActivateConfig, state state.WritableState) cluster.ResponseWithError {
configs := state.Configs().GetByIds([]string{activateConfig.ConfigId})
if len(configs) == 0 {
return cluster.NewResponseErrorf(codes2.NotFound, "config with id %s not found", activateConfig.ConfigId)
@@ -70,9 +73,9 @@ func (configService) HandleActivateConfigCommand(activateConfig cluster.Activate
config := configs[0]
affected := state.WritableConfigs().Activate(config, activateConfig.Date)
if holder.ClusterClient.IsLeader() {
for _, c := range affected {
for i := range affected {
// TODO handle db errors
_, err := model.ConfigRep.Upsert(c)
_, err := model.ConfigRep.Upsert(affected[i])
if err != nil {
log.WithMetadata(map[string]interface{}{
"config": config,
@@ -157,8 +160,8 @@ func (cs configService) HandleUpsertConfigCommand(upsertConfig cluster.UpsertCon
}
func (cs configService) BroadcastNewConfig(state state.ReadonlyState, configs ...entity.Config) {
for _, cfg := range configs {
moduleID := cfg.ModuleId
for i := range configs {
moduleID := configs[i].ModuleId
module := state.Modules().GetById(moduleID)
moduleName := module.Name
room := moduleName + ConfigWatchersRoomSuffix
@@ -187,20 +190,22 @@ func (cs configService) broadcast(room, event string, data []byte) {
func (configService) validateSchema(schema entity.ConfigSchema, data map[string]interface{}) (bool, error) {
schemaLoader := gojsonschema.NewGoLoader(schema.Schema)
documentLoader := gojsonschema.NewGoLoader(data)
if result, err := gojsonschema.Validate(schemaLoader, documentLoader); err != nil {
result, err := gojsonschema.Validate(schemaLoader, documentLoader)
if err != nil {
return false, err
} else if result.Valid() {
return true, nil
} else {
desc := make(map[string]string)
for _, value := range result.Errors() {
desc[value.Field()] = value.Description()
}
return false, validationSchemaError{Description: desc}
}
desc := make(map[string]string)
for _, value := range result.Errors() {
desc[value.Field()] = value.Description()
}
return false, validationSchemaError{Description: desc}
}
func mergeNestedMaps(maps ...map[string]interface{}) map[string]interface{} {
//nolint gomnd
if len(maps) == 1 {
return maps[0]
}
+9 -3
View File
@@ -3,6 +3,9 @@ package service
import (
"context"
"encoding/json"
"sync"
"time"
"github.com/cenkalti/backoff"
etp "github.com/integration-system/isp-etp-go"
"github.com/integration-system/isp-lib/structure"
@@ -11,8 +14,11 @@ import (
"isp-config-service/codes"
"isp-config-service/holder"
"isp-config-service/store/state"
"sync"
"time"
)
const (
messagesBackoffInterval = 100 * time.Millisecond
messagesBackoffMaxRetries = 3
)
var (
@@ -92,7 +98,7 @@ func (ds *discoveryService) sendAddrList(conn etp.Conn, event string, addressLis
if err != nil {
return err
}
bf := backoff.WithMaxRetries(backoff.NewConstantBackOff(100*time.Millisecond), 3)
bf := backoff.WithMaxRetries(backoff.NewConstantBackOff(messagesBackoffInterval), messagesBackoffMaxRetries)
err = backoff.Retry(func() error {
return conn.Emit(context.Background(), event, bytes)
}, bf)
+10 -9
View File
@@ -1,6 +1,8 @@
package service
import (
"sort"
"github.com/integration-system/isp-lib/structure"
log "github.com/integration-system/isp-log"
"isp-config-service/cluster"
@@ -10,7 +12,6 @@ import (
"isp-config-service/holder"
"isp-config-service/model"
"isp-config-service/store/state"
"sort"
)
var (
@@ -67,8 +68,8 @@ func (moduleRegistryService) HandleDeleteModulesCommand(deleteModules cluster.De
configsToDelete := state.WritableConfigs().GetByModuleIds(ids)
confIds := make([]string, 0, len(configsToDelete))
for _, conf := range configsToDelete {
confIds = append(confIds, conf.Id)
for i := range configsToDelete {
confIds = append(confIds, configsToDelete[i].Id)
}
state.WritableConfigs().DeleteByIds(confIds)
@@ -124,14 +125,14 @@ func (moduleRegistryService) GetAggregatedModuleInfo(state state.ReadonlyState)
}
configs := state.Configs().GetByModuleIds(idList)
for _, cfg := range configs {
info := resMap[cfg.ModuleId]
for i := range configs {
info := resMap[configs[i].ModuleId]
info.Configs = append(info.Configs, domain.ConfigModuleInfo{
Config: cfg,
Config: configs[i],
Valid: false,
})
resMap[cfg.ModuleId] = info
resMap[configs[i].ModuleId] = info
}
schemas := state.Schemas().GetByModuleIds(idList)
for _, s := range schemas {
@@ -139,8 +140,8 @@ func (moduleRegistryService) GetAggregatedModuleInfo(state state.ReadonlyState)
schema := s.Schema
info.ConfigSchema = &schema
for i, config := range info.Configs {
dataForValidate := ConfigService.CompileConfig(config.Data, state, config.CommonConfigs...)
for i := range info.Configs {
dataForValidate := ConfigService.CompileConfig(info.Configs[i].Data, state, info.Configs[i].CommonConfigs...)
info.Configs[i].Valid, _ = ConfigService.validateSchema(s, dataForValidate)
}
+2 -2
View File
@@ -3,6 +3,7 @@ package service
import (
"context"
"encoding/json"
"github.com/cenkalti/backoff"
etp "github.com/integration-system/isp-etp-go"
"github.com/integration-system/isp-lib/structure"
@@ -11,7 +12,6 @@ import (
"isp-config-service/codes"
"isp-config-service/holder"
"isp-config-service/store/state"
"time"
)
const (
@@ -63,7 +63,7 @@ func (rs *routesService) sendRoutes(conn etp.Conn, event string, routes structur
if bytes, err := json.Marshal(routes); err != nil {
return err
} else {
bf := backoff.WithMaxRetries(backoff.NewConstantBackOff(100*time.Millisecond), 3)
bf := backoff.WithMaxRetries(backoff.NewConstantBackOff(messagesBackoffInterval), messagesBackoffMaxRetries)
err := backoff.Retry(func() error {
return conn.Emit(context.Background(), event, bytes)
}, bf)
+15 -12
View File
@@ -1,8 +1,9 @@
package state
import (
"isp-config-service/entity"
"time"
"isp-config-service/entity"
)
const (
@@ -29,8 +30,9 @@ type ConfigStore struct {
}
func (cs ConfigStore) GetActiveByModuleId(moduleId string) *entity.Config {
for _, conf := range cs.Configs {
if conf.ModuleId == moduleId && conf.Active {
for i := range cs.Configs {
if cs.Configs[i].ModuleId == moduleId && cs.Configs[i].Active {
conf := cs.Configs[i]
return &conf
}
}
@@ -40,9 +42,9 @@ func (cs ConfigStore) GetActiveByModuleId(moduleId string) *entity.Config {
func (cs ConfigStore) GetByIds(ids []string) []entity.Config {
idsMap := StringsToMap(ids)
result := make([]entity.Config, 0, len(ids))
for _, conf := range cs.Configs {
if _, ok := idsMap[conf.Id]; ok {
result = append(result, conf)
for i := range cs.Configs {
if _, ok := idsMap[cs.Configs[i].Id]; ok {
result = append(result, cs.Configs[i])
}
}
return result
@@ -51,9 +53,9 @@ func (cs ConfigStore) GetByIds(ids []string) []entity.Config {
func (cs ConfigStore) GetByModuleIds(ids []string) []entity.Config {
idsMap := StringsToMap(ids)
result := make([]entity.Config, 0, len(ids))
for _, conf := range cs.Configs {
if _, ok := idsMap[conf.ModuleId]; ok {
result = append(result, conf)
for i := range cs.Configs {
if _, ok := idsMap[cs.Configs[i].ModuleId]; ok {
result = append(result, cs.Configs[i])
}
}
return result
@@ -61,6 +63,7 @@ func (cs ConfigStore) GetByModuleIds(ids []string) []entity.Config {
func (cs *ConfigStore) Create(config entity.Config) entity.Config {
config.Version = cs.calcNewVersion(config.ModuleId)
//nolint gomnd
if config.Version == 1 {
config.Active = true
}
@@ -137,10 +140,10 @@ func (cs *ConfigStore) deactivate(moduleId string, date time.Time) []entity.Conf
func (cs *ConfigStore) FilterByCommonConfigs(commonIds []string) []entity.Config {
idsMap := StringsToMap(commonIds)
result := make([]entity.Config, 0)
for _, cfg := range cs.Configs {
for _, commonId := range cfg.CommonConfigs {
for i := range cs.Configs {
for _, commonId := range cs.Configs[i].CommonConfigs {
if _, ok := idsMap[commonId]; ok {
result = append(result, cfg)
result = append(result, cs.Configs[i])
break
}
}
+2 -1
View File
@@ -79,7 +79,8 @@ func NewState() *State {
}
}
func NewStateFromSnapshot(configs []entity.Config, schemas []entity.ConfigSchema, modules []entity.Module, commConfigs []entity.CommonConfig) *State {
func NewStateFromSnapshot(configs []entity.Config, schemas []entity.ConfigSchema,
modules []entity.Module, commConfigs []entity.CommonConfig) *State {
return &State{
MeshStore: NewMesh(),
ConfigsStore: &ConfigStore{Configs: configs},
+4 -3
View File
@@ -3,16 +3,17 @@ package store
import (
"encoding/binary"
"fmt"
"io"
"sync"
"github.com/hashicorp/raft"
log "github.com/integration-system/isp-log"
jsoniter "github.com/json-iterator/go"
"github.com/mohae/deepcopy"
"github.com/pkg/errors"
"io"
"isp-config-service/cluster"
"isp-config-service/codes"
"isp-config-service/store/state"
"sync"
)
var (
@@ -29,7 +30,7 @@ func (s *Store) Apply(l *raft.Log) interface{} {
s.lock.Lock()
defer s.lock.Unlock()
if len(l.Data) < 8 {
if len(l.Data) < cluster.CommandSizeBytes {
log.Errorf(codes.ApplyLogCommandError, "invalid log data command: %s", l.Data)
}
command := binary.BigEndian.Uint64(l.Data[:8])
+3 -3
View File
@@ -8,20 +8,20 @@ import (
"isp-config-service/holder"
)
func (h *SocketEventHandler) applyCommandOnLeader(_ etp.Conn, cmd []byte) []byte {
func (h *SocketEventHandler) applyCommandOnLeader(_ etp.Conn, cmd []byte) (data []byte) {
cmdCopy := make([]byte, len(cmd))
copy(cmdCopy, cmd)
obj, err := holder.ClusterClient.SyncApplyOnLeader(cmdCopy)
if err != nil {
var logResponse cluster.ApplyLogResponse
logResponse.ApplyError = err.Error()
data, err := json.Marshal(obj)
data, err = json.Marshal(obj)
if err != nil {
log.Fatalf(codes.SyncApplyError, "marshaling ApplyLogResponse: %v", err)
}
return data
}
data, err := json.Marshal(obj)
data, err = json.Marshal(obj)
if err != nil {
log.Fatalf(codes.SyncApplyError, "marshaling ApplyLogResponse: %v", err)
}