From 445389b7d87609a1ea0d219667dda7fdc8979275 Mon Sep 17 00:00:00 2001 From: Maxim Merzhanov Date: Thu, 10 Oct 2019 11:18:29 +0300 Subject: [PATCH] - implement raft logger - replace logger with isp-log - add storage layer (pq) --- Gopkg.lock | 116 +++++++++++++++++------- Gopkg.toml | 9 ++ cluster/client.go | 12 +-- cluster/const.go | 5 +- cluster/leader_client.go | 11 ++- codes/codes.go | 40 ++++++++ conf/configuration.go | 2 +- entity/config.go | 27 +++++- entity/instance.go | 11 --- entity/module.go | 10 +- main.go | 54 +++++------ migrations/00007_2019-10-08_init_v2.sql | 48 ++++++++++ model/client.go | 22 +++++ model/common_config.go | 49 ++++++++++ model/config.go | 49 ++++++++++ model/module.go | 48 ++++++++++ model/schema.go | 36 ++++++++ raft/logger.go | 106 ++++++++++++++++++++++ raft/manager.go | 2 + service/clusterstate.go | 3 - service/discovery.go | 41 +++++---- service/routes.go | 29 ++++-- store/apply.go | 10 +- store/restore.go | 38 ++++++++ store/state/common_config.go | 24 +++++ store/state/configs.go | 33 +++++++ store/state/modules.go | 30 ++++++ store/state/schemas.go | 25 +++++ store/state/state.go | 23 ++++- store/store.go | 21 ++--- subs/client.go | 18 ++-- subs/root.go | 14 ++- ws/conn.go | 8 +- 33 files changed, 811 insertions(+), 163 deletions(-) create mode 100644 codes/codes.go delete mode 100644 entity/instance.go create mode 100644 migrations/00007_2019-10-08_init_v2.sql create mode 100644 model/client.go create mode 100644 model/common_config.go create mode 100644 model/config.go create mode 100644 model/module.go create mode 100644 model/schema.go create mode 100644 raft/logger.go create mode 100644 store/restore.go create mode 100644 store/state/common_config.go create mode 100644 store/state/configs.go create mode 100644 store/state/modules.go create mode 100644 store/state/schemas.go diff --git a/Gopkg.lock b/Gopkg.lock index aa295a6..5df4e55 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -1,14 +1,6 @@ # This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. -[[projects]] - digest = "1:e92f5581902c345eb4ceffdcd4a854fb8f73cf436d47d837d1ec98ef1fe0a214" - name = "github.com/StackExchange/wmi" - packages = ["."] - pruneopts = "UT" - revision = "5d049714c4a64225c3c79a7cf7d02f7fb5b96338" - version = "1.0.0" - [[projects]] branch = "master" digest = "1:7a9140c806333a78122763d08ec6c0d7358c7fff1df8cfbb01881c5dc46e24e5" @@ -58,15 +50,22 @@ version = "v1.4.7" [[projects]] - digest = "1:440028f55cb322d8cb5b9d5ebec298a00b7d74690a658fe6b1c0c0b44341bfae" - name = "github.com/go-ole/go-ole" + digest = "1:f9448bfab8ebe44e3d91e4e4475cf92d60789a614652f361df4e41972c9d5caf" + name = "github.com/go-pg/pg" packages = [ ".", - "oleutil", + "internal", + "internal/iszero", + "internal/parser", + "internal/pool", + "internal/struct_filter", + "internal/tag", + "orm", + "types", ] pruneopts = "UT" - revision = "97b6244175ae18ea6eef668034fd6565847501c9" - version = "v1.2.4" + revision = "1d957cb20f319c4a1e2db7d345824c12aefe5943" + version = "v8.0.6" [[projects]] digest = "1:07f4fafe81587b642166199f41c3edcca12929fcfcc0261b00be5dea2f968f44" @@ -164,12 +163,12 @@ version = "v1.0.0" [[projects]] - digest = "1:27a5032b785c980b947d6dedb6061647f557fadc3141ce79569f89cef4932acf" + branch = "master" + digest = "1:793af7eb674c40d9bb472c26e2c1a2eb20407f189dd995f72f58c23bfaea18bc" name = "github.com/hashicorp/raft" packages = ["."] pruneopts = "UT" - revision = "ff523e1c1515a5b33cc3153a34c984093fed06bb" - version = "v1.1.1" + revision = "7d1d8f1e35633442c29f894aba099ac90cd04f2b" [[projects]] branch = "master" @@ -213,32 +212,51 @@ revision = "24b88aed7c77403c0b9b45de1f42ddc3c4fc0fb2" [[projects]] - digest = "1:86431b6d676940fee5c9fa74cc730041a33454271ca5069caa72049c77445dd0" + branch = "master" + digest = "1:50757af2a33b01c2ad349659740367c41739eb03e8c4010e566e0b5bd2031720" name = "github.com/integration-system/isp-lib" packages = [ "backend", "bootstrap", "config", "config/schema", + "database", "logger", "metric", "proto/stubs", - "socket", "streaming", "structure", "utils", ] pruneopts = "UT" - revision = "d2cc77b8fb8648ae7f8efdf1d1b834e8e57b56d7" - version = "v1.5.2" + revision = "ef90e94729c8d6fbb34b3ebf033b8d6ffecadb37" [[projects]] branch = "master" - digest = "1:48f3a739fabefebf152d0196277ee89136c1fa6d88fc67fa486fc765a05b1caa" + digest = "1:21b7454a3f43dc141a1b48ef954bd98a506aa9aab599d9ec214a324b9864b49b" + name = "github.com/integration-system/isp-log" + packages = [ + ".", + "stdcodes", + ] + pruneopts = "UT" + revision = "d1d067bfc8eaa1de1d70da37578322ec72e0af04" + +[[projects]] + branch = "master" + digest = "1:9eb3b0c24935048c4097eedb3344f2f209e35bd12fa3884e54b83a1a55c22224" name = "github.com/integration-system/jsonschema" packages = ["."] pruneopts = "UT" - revision = "5475a8b08e62e41fa886641861ac225e7f91e4e5" + revision = "26ce276eb6ea02881e72f7756f48796bc1f9552b" + +[[projects]] + digest = "1:01ed62f8f4f574d8aff1d88caee113700a2b44c42351943fa73cc1808f736a50" + name = "github.com/jinzhu/inflection" + packages = ["."] + pruneopts = "UT" + revision = "f5c5f50e6090ae76a29240b61ae2a90dd810112e" + version = "v1.0.0" [[projects]] digest = "1:ac7f1061abc812a5d0de6df7e3f477cef942aef503848f436da0f0eb2603bfbf" @@ -279,6 +297,18 @@ revision = "f55edac94c9bbba5d6182a4be46d86a2c9b5b50e" version = "v1.0.2" +[[projects]] + digest = "1:12cb143f2148bf54bcd9fe622abac17325e85eeb1d84b8ec6caf1c80232108fd" + name = "github.com/lib/pq" + packages = [ + ".", + "oid", + "scram", + ] + pruneopts = "UT" + revision = "3427c32cb71afc948325f299f040e53c1dd78979" + version = "v1.2.0" + [[projects]] digest = "1:5a0ef768465592efca0412f7e838cdc0826712f8447e70e6ccc52eb441e9ab13" name = "github.com/magiconair/properties" @@ -359,6 +389,14 @@ revision = "ba968bfe8b2f7e042a574c888954fccecfa385b4" version = "v0.8.1" +[[projects]] + digest = "1:7d99649602f68b73ade640ca6975ccc38735f329e159c6a507b63f00213678c0" + name = "github.com/pressly/goose" + packages = ["."] + pruneopts = "UT" + revision = "e4b98955473e91a12fc7d8816c28d06376d1d92c" + version = "v2.6.0" + [[projects]] branch = "master" digest = "1:5bbebe8ac19ecb6c87790a89faa20566e38ed0d6494a1d14c4f5b05d9ce2436c" @@ -367,17 +405,6 @@ pruneopts = "UT" revision = "cac0b30c2563378d434b5af411844adff8e32960" -[[projects]] - digest = "1:f5139e9f4441369ffb5d44fa9fae62b921457d4dc09cd873ed0fd44511cc87ee" - name = "github.com/shirou/gopsutil" - packages = [ - "cpu", - "internal/common", - ] - pruneopts = "UT" - revision = "d80c43f9c984a48783daf22f4bd9278006ae483a" - version = "v2.19.7" - [[projects]] digest = "1:04457f9f6f3ffc5fea48e71d62f2ca256637dee0a04d710288e27e05c8b41976" name = "github.com/sirupsen/logrus" @@ -467,9 +494,12 @@ [[projects]] branch = "master" - digest = "1:bbe51412d9915d64ffaa96b51d409e070665efc5194fcf145c4a27d4133107a4" + digest = "1:35ce874cf16f78a2da908ab28b0277497e36603d289db00d39da5200bc8ace08" name = "golang.org/x/crypto" - packages = ["ssh/terminal"] + packages = [ + "pbkdf2", + "ssh/terminal", + ] pruneopts = "UT" revision = "4def268fd1a49955bfb3dda92fe3db4f924f2285" @@ -586,13 +616,24 @@ revision = "51d6538a90f86fe93ac480b35f37b2be17fef232" version = "v2.2.2" +[[projects]] + digest = "1:999d566ad1ae4303c456af5a155f7b42401cca4fd33552567ed9dd997b107a08" + name = "mellium.im/sasl" + packages = ["."] + pruneopts = "UT" + revision = "e58e780e1378aa4df5dc705364ff5ae9a4dd1e04" + source = "https://github.com/mellium/sasl.git" + version = "v0.2.1" + [solve-meta] analyzer-name = "dep" analyzer-version = 1 input-imports = [ "github.com/asaskevich/govalidator", "github.com/cenkalti/backoff", + "github.com/go-pg/pg", "github.com/googollee/go-socket.io", + "github.com/hashicorp/go-hclog", "github.com/hashicorp/raft", "github.com/hashicorp/raft-boltdb", "github.com/integration-system/golang-socketio", @@ -600,12 +641,17 @@ "github.com/integration-system/isp-lib/bootstrap", "github.com/integration-system/isp-lib/config", "github.com/integration-system/isp-lib/config/schema", + "github.com/integration-system/isp-lib/database", "github.com/integration-system/isp-lib/logger", "github.com/integration-system/isp-lib/structure", "github.com/integration-system/isp-lib/utils", + "github.com/integration-system/isp-log", + "github.com/integration-system/isp-log/stdcodes", "github.com/json-iterator/go", "github.com/mohae/deepcopy", "github.com/pkg/errors", + "github.com/sirupsen/logrus", + "github.com/spf13/cast", "github.com/thecodeteam/goodbye", ] solver-name = "gps-cdcl" diff --git a/Gopkg.toml b/Gopkg.toml index 7314aec..97eedb1 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -36,6 +36,10 @@ name = "github.com/valyala/fasthttp" branch = "master" +[[override]] + name = "github.com/integration-system/isp-lib" + branch = "master" + [[override]] name = "github.com/googollee/go-socket.io" revision = "c8aeb1ed9b49d7de8fef8662efb18f1d289c5f2e" @@ -44,3 +48,8 @@ name = "github.com/googollee/go-engine.io" revision = "e2f255711dcb2ea41e42c6d9d98c172d7edf6509" +[[override]] + name = "github.com/hashicorp/raft" + branch = "master" + + diff --git a/cluster/client.go b/cluster/client.go index 33c6402..fca390e 100644 --- a/cluster/client.go +++ b/cluster/client.go @@ -2,8 +2,9 @@ package cluster import ( "errors" - "github.com/integration-system/isp-lib/logger" "github.com/integration-system/isp-lib/structure" + log "github.com/integration-system/isp-log" + "isp-config-service/codes" "isp-config-service/raft" "strconv" "sync" @@ -74,7 +75,6 @@ func (client *ClusterClient) SyncApplyOnLeader(command []byte) (interface{}, err func (client *ClusterClient) listenLeader() { for n := range client.r.LeaderCh() { - logger.Debug("ChangeLeaderNotification:", n) client.leaderMu.Lock() if client.leaderState.leaderAddr != n.CurrentLeaderAddress { if client.leaderClient != nil { @@ -87,7 +87,7 @@ func (client *ClusterClient) listenLeader() { client.onClientDisconnect(client.leaderState.leaderAddr) }) if err := leaderClient.Dial(leaderConnectionTimeout); err != nil { - logger.Fatalf("could not connect to leader: %v", err) + log.Fatalf(codes.ConnectToLeaderError, "could not connect to leader: %v", err) continue } go func(declaration structure.BackendDeclaration) { @@ -96,9 +96,9 @@ func (client *ClusterClient) listenLeader() { response = res } if err != nil { - logger.Warn("leaderClient.SendDeclaration", err) + log.Warnf(codes.SendDeclarationToLeaderError, "send declaration to leader err: %v", err) } else if response != "ok" { - logger.Warn("leaderClient.SendDeclaration response", response) + log.Warnf(codes.SendDeclarationToLeaderError, "send declaration to leader response: %s", response) } }(client.declaration) @@ -107,7 +107,7 @@ func (client *ClusterClient) listenLeader() { go func(declaration structure.BackendDeclaration) { command := PrepareUpdateBackendDeclarationCommand(declaration) i, err := client.SyncApply(command) - logger.Debug("cluster.SyncApply announce myself:", i, err) + log.Debugf(0, "cluster.SyncApply announce myself:%v, %v", i, err) }(client.declaration) } client.leaderState = leaderState{ diff --git a/cluster/const.go b/cluster/const.go index 18ad1da..28bfa28 100644 --- a/cluster/const.go +++ b/cluster/const.go @@ -4,8 +4,9 @@ import ( "bytes" "encoding/binary" "encoding/json" - "github.com/integration-system/isp-lib/logger" "github.com/integration-system/isp-lib/structure" + log "github.com/integration-system/isp-log" + "isp-config-service/codes" ) const ( @@ -34,7 +35,7 @@ func prepareCommand(command uint64, payload interface{}) []byte { buf := bytes.NewBuffer(cmd) err := json.NewEncoder(buf).Encode(payload) if err != nil { - logger.Fatal("prepareCommand json encoding", err) + log.Fatalf(codes.PrepareLogCommandError, "prepare log command: %v", err) } return buf.Bytes() } diff --git a/cluster/leader_client.go b/cluster/leader_client.go index c612d8e..b10f55a 100644 --- a/cluster/leader_client.go +++ b/cluster/leader_client.go @@ -6,9 +6,10 @@ import ( "github.com/cenkalti/backoff" gosocketio "github.com/integration-system/golang-socketio" "github.com/integration-system/isp-lib/config" - "github.com/integration-system/isp-lib/logger" "github.com/integration-system/isp-lib/structure" "github.com/integration-system/isp-lib/utils" + log "github.com/integration-system/isp-log" + "isp-config-service/codes" "isp-config-service/conf" "net" "strconv" @@ -50,15 +51,17 @@ func NewSocketLeaderClient(address string, leaderDisconnectionCallback func()) * EnableReconnection(). ReconnectionTimeout(1 * time.Second). OnReconnectionError(func(err error) { - logger.Warnf("socket.io leader(%s) client reconnection err: %v", socketIoAddress, err) + log.Warnf(codes.LeaderClientReconnectionError, "leader client reconnection err: %v", err) }). BuildToConnect(socketIoAddress) err := client.On(gosocketio.OnDisconnection, func(channel *gosocketio.Channel) { - logger.Debugf("[%s]:%s", channel.Ip(), "LeaderClient OnDisconnection") + log.WithMetadata(map[string]interface{}{ + "leaderIp": channel.Ip(), + }).Warn(codes.LeaderClientDisconnected, "leaderclient disconnected") leaderDisconnectionCallback() }) if err != nil { - logger.Fatal(err) + log.Fatalf(codes.LeaderClientBindError, "leader client unable to bind event. err: %v", err) } return &SocketLeaderClient{ c: client, diff --git a/codes/codes.go b/codes/codes.go new file mode 100644 index 0000000..a998104 --- /dev/null +++ b/codes/codes.go @@ -0,0 +1,40 @@ +package codes + +// TODO numbers +const ( + // Common + StartHttpServerError = 0 + ShutdownHttpServerError = 0 + ShutdownHttpServerInfo = 0 + + ConfigDataSerializeError = 0 + SocketIoError = 0 + + // Raft + InitRaftError = 0 + RestoreFromRepositoryError = 0 + RaftLoggerCode = 0 + BootstrapClusterError = 0 + RaftShutdownError = 0 + RaftShutdownInfo = 0 + + // Raft Log + InvalidLogDataCommand = 0 + ApplyLogCommandError = 0 + UnknownLogCommand = 0 + PrepareLogCommandError = 0 + SyncApplyError = 0 + + // Raft Cluster + ConnectToLeaderError = 0 + SendDeclarationToLeaderError = 0 + LeaderClientReconnectionError = 0 + LeaderClientDisconnected = 0 + LeaderClientBindError = 0 + + // Services + DiscoveryServiceError = 0 + RoutesServiceError = 0 + + DeleteBackendDeclarationError = 0 +) diff --git a/conf/configuration.go b/conf/configuration.go index eb8d53d..0cc9c1b 100644 --- a/conf/configuration.go +++ b/conf/configuration.go @@ -5,7 +5,7 @@ import ( ) type Configuration struct { - Database structure.DBConfiguration `valid:"required~Required"` + Database structure.DBConfiguration `valid:"required~Required" schema:"База данных,настройка параметров подключения к базе данных"` GrpcOuterAddress structure.AddressConfiguration `valid:"required~Required" json:"grpcOuterAddress"` ModuleName string `valid:"required~Required"` WS struct { diff --git a/entity/config.go b/entity/config.go index 103284d..9051098 100644 --- a/entity/config.go +++ b/entity/config.go @@ -3,7 +3,8 @@ package entity import ( "encoding/json" "github.com/integration-system/isp-lib/config/schema" - "github.com/integration-system/isp-lib/logger" + log "github.com/integration-system/isp-log" + "isp-config-service/codes" "time" ) @@ -13,25 +14,41 @@ func (cd ConfigData) ToJSON() string { if bytes, err := json.Marshal(cd); err == nil { return string(bytes) } else { - logger.Warn("Could not serialize config data to JSON", err) + log.Warnf(codes.ConfigDataSerializeError, "could not serialize config data to JSON %v", err) return "{}" } } type Config struct { - Id int64 `json:"id"` + tableName string `sql:"?db_schema.configs" json:"-"` + Id int64 `json:"id"` + Uuid string `json:"uuid" valid:"required~Required,uuid~must be a valid uuid"` + Name string `json:"name" valid:"required~Required"` + CommonConfigs []string `json:"commonConfigIds" pg:",array"` + Description string `json:"description"` + ModuleId int32 `json:"moduleId" valid:"required~Required"` + Version int32 `json:"version" sql:",null"` + Active bool `json:"active" sql:",null"` + CreatedAt time.Time `json:"createdAt" sql:",null"` + UpdatedAt time.Time `json:"updatedAt" sql:",null"` + Data ConfigData `json:"data" sql:",notnull"` +} + +type CommonConfig struct { + tableName string `sql:"?db_schema.common_configs" json:"-"` + Uuid string `json:"uuid" valid:"required~Required,uuid~must be a valid uuid"` Name string `json:"name" valid:"required~Required"` Description string `json:"description"` - ModuleId int32 `json:"moduleId" valid:"required~Required"` Version int32 `json:"version" sql:",null"` - Active bool `json:"active" sql:",null"` CreatedAt time.Time `json:"createdAt" sql:",null"` UpdatedAt time.Time `json:"updatedAt" sql:",null"` Data ConfigData `json:"data" sql:",notnull"` } type ConfigSchema struct { + tableName string `sql:"?db_schema.config_schemas" json:"-"` Id int32 + Uuid string `json:"uuid" valid:"required~Required,uuid~must be a valid uuid"` Version string ModuleId int32 Schema schema.Schema diff --git a/entity/instance.go b/entity/instance.go deleted file mode 100644 index fb4ddd4..0000000 --- a/entity/instance.go +++ /dev/null @@ -1,11 +0,0 @@ -package entity - -import "time" - -type Instance struct { - Id int32 `json:"id"` - Uuid string `json:"uuid" valid:"required~Required,uuid~must be a valid uuid"` - Name string `json:"name" valid:"required~Required"` - // CreatedAtJson utils.JSONTime `json:"createdAt" sql:"-"` - CreatedAt time.Time `json:"createdAt" sql:",null"` -} diff --git a/entity/module.go b/entity/module.go index bd0c3bf..a263e5e 100644 --- a/entity/module.go +++ b/entity/module.go @@ -3,16 +3,12 @@ package entity import "time" type Module struct { + tableName string `sql:"?db_schema.modules" json:"-"` Id int32 `json:"id"` - InstanceId int32 `json:"instanceId" valid:"required~Required"` + Uuid string `json:"uuid" valid:"required~Required,uuid~must be a valid uuid"` Name string `json:"name" valid:"required~Required"` - Active bool `json:"active" sql:",null"` + Active bool `json:"active" sql:"-"` CreatedAt time.Time `json:"createdAt" sql:",null"` LastConnectedAt time.Time `json:"lastConnectedAt"` LastDisconnectedAt time.Time `json:"lastDisconnectedAt"` } - -type ModuleInstanceIdentity struct { - Name string `valid:"required~Required"` - Uuid string `valid:"required~Required,uuid~must be a valid uuid"` -} diff --git a/main.go b/main.go index c402d54..66c7153 100644 --- a/main.go +++ b/main.go @@ -5,13 +5,15 @@ import ( "github.com/integration-system/isp-lib/backend" "github.com/integration-system/isp-lib/bootstrap" "github.com/integration-system/isp-lib/config" - "github.com/integration-system/isp-lib/logger" "github.com/integration-system/isp-lib/structure" + log "github.com/integration-system/isp-log" "github.com/thecodeteam/goodbye" "isp-config-service/cluster" + "isp-config-service/codes" "isp-config-service/conf" "isp-config-service/helper" "isp-config-service/holder" + "isp-config-service/model" "isp-config-service/raft" "isp-config-service/service" "isp-config-service/store" @@ -51,8 +53,9 @@ func main() { Address: cfg.WS.Grpc, } - client, store := initRaft(cfg.WS.Raft.GetAddress(), cfg.Cluster, declaration) - initWebsocket(cfg.WS.Rest.GetAddress(), client, store) + model.DbClient.ReceiveConfiguration(cfg.Database) + client, raftStore := initRaft(cfg.WS.Raft.GetAddress(), cfg.Cluster, declaration) + initWebsocket(cfg.WS.Rest.GetAddress(), client, raftStore) initGrpc(cfg.WS.Grpc) ctx := context.Background() @@ -63,35 +66,34 @@ func main() { <-shutdownChan } -func initWebsocket(bindAddress string, clusterClient *cluster.ClusterClient, store *store.Store) { +func initWebsocket(bindAddress string, clusterClient *cluster.ClusterClient, raftStore *store.Store) { socket, err := ws.NewWebsocketServer() if err != nil { - logger.Fatal(err) + // TODO уйдет при миграции + log.Fatalf(0, "init socket.io %s", err.Error()) } - subs.NewSocketEventHandler(socket, clusterClient, store).SubscribeAll() + subs.NewSocketEventHandler(socket, clusterClient, raftStore).SubscribeAll() mux := http.NewServeMux() mux.HandleFunc("/socket.io/", socket.ServeHttp) httpServer := &http.Server{Addr: bindAddress, Handler: mux} go func() { if err := httpServer.ListenAndServe(); err != nil { - logger.Fatal(err) + log.Fatalf(codes.StartHttpServerError, "unable to start http server. %v", err) } }() holder.Socket = socket holder.HttpServer = httpServer - - logger.Infof("socket.IO server start on %s", bindAddress) } func initRaft(bindAddress string, clusterCfg conf.ClusterConfiguration, declaration structure.BackendDeclaration) (*cluster.ClusterClient, *store.Store) { - store := store.NewStateStore() - r, err := raft.NewRaft(bindAddress, clusterCfg, store) + raftStore := store.NewStateStoreFromRepository() + r, err := raft.NewRaft(bindAddress, clusterCfg, raftStore) if err != nil { - logger.Fatal(err) + log.Fatalf(codes.InitRaftError, "unable to create raft server. %v", err) } clusterClient := cluster.NewRaftClusterClient(r, declaration, func(address string) { - store.VisitState(func(s state.State) { + raftStore.VisitState(func(s state.State) { cfg := config.Get().(*conf.Configuration) addr, err := net.ResolveTCPAddr("tcp", address) if err != nil { @@ -113,7 +115,7 @@ func initRaft(bindAddress string, clusterCfg conf.ClusterConfiguration, declarat back := structure.BackendDeclaration{ModuleName: cfg.ModuleName, Address: addressConfiguration} _, err = service.ClusterStateService.HandleDeleteBackendDeclarationCommand(back, s) if err != nil { - logger.Debug("onClientDisconnect HandleDeleteBackendDeclarationCommand", address, err) + log.Warnf(codes.DeleteBackendDeclarationError, "onClientDisconnect delete backend declaration. %v", err) } }) }) @@ -121,17 +123,14 @@ func initRaft(bindAddress string, clusterCfg conf.ClusterConfiguration, declarat err = r.BootstrapCluster() // err can be ignored if err != nil { - logger.Error("BootstrapCluster err:", err) + log.Errorf(codes.BootstrapClusterError, "bootstrap cluster. %v", err) } - - logger.Infof("raft server start on %s", bindAddress) - - return clusterClient, store + return clusterClient, raftStore } func initGrpc(bindAddress structure.AddressConfiguration) { - service := backend.GetDefaultService(moduleName, helper.GetAllHandlers()...) - backend.StartBackendGrpcServer(bindAddress, service) + defaultService := backend.GetDefaultService(moduleName, helper.GetAllHandlers()...) + backend.StartBackendGrpcServer(bindAddress, defaultService) } func onShutdown(ctx context.Context, sig os.Signal) { @@ -140,20 +139,21 @@ func onShutdown(ctx context.Context, sig os.Signal) { backend.StopGrpcServer() if err := holder.ClusterClient.Shutdown(); err != nil { - logger.Warnf("raft shutdown err: %v", err) + log.Warnf(codes.RaftShutdownError, "raft shutdown err: %v", err) } else { - logger.Info("raft shutdown success") + log.Info(codes.RaftShutdownInfo, "raft shutdown success") } if err := holder.Socket.Close(); err != nil { - logger.Warnf("socket.io shutdown err: %v", err) + // TODO уйдет при миграции + log.Warnf(0, "socket.io shutdown err: %s", err.Error()) } else { - logger.Info("socket.io shutdown success") + log.Info(0, "socket.io shutdown success") } if err := holder.HttpServer.Shutdown(ctx); err != nil { - logger.Warnf("http server shutdown err: %v", err) + log.Warnf(codes.ShutdownHttpServerError, "http server shutdown err: %v", err) } else { - logger.Info("http server shutdown success") + log.Info(codes.ShutdownHttpServerInfo, "http server shutdown success") } } diff --git a/migrations/00007_2019-10-08_init_v2.sql b/migrations/00007_2019-10-08_init_v2.sql new file mode 100644 index 0000000..cf0e58c --- /dev/null +++ b/migrations/00007_2019-10-08_init_v2.sql @@ -0,0 +1,48 @@ +-- +goose Up + +DROP TABLE instances CASCADE; + +ALTER TABLE configs + ADD COLUMN uuid UUID NOT NULL DEFAULT uuid_generate_v4(), + ADD COLUMN common_configs UUID[] NOT NULL DEFAULT '{}', + ADD CONSTRAINT "unique_configs_uuid" UNIQUE ("uuid"); + +ALTER TABLE config_schemas + ADD COLUMN uuid UUID NOT NULL DEFAULT uuid_generate_v4(), + ADD CONSTRAINT "unique_config_schemas_uuid" UNIQUE ("uuid"); + +ALTER TABLE modules + ADD COLUMN uuid UUID NOT NULL DEFAULT uuid_generate_v4(), + ADD CONSTRAINT "unique_modules_uuid" UNIQUE ("uuid"); + + +CREATE TABLE common_configs +( + id serial4 NOT NULL PRIMARY KEY, + uuid UUID NOT NULL, + name VARCHAR(255) NOT NULL DEFAULT 'unnamed', + description TEXT, + version int4 NOT NULL, + active bool NOT NULL DEFAULT false, + created_at timestamp NOT NULL DEFAULT (now() at time zone 'utc'), + updated_at timestamp NOT NULL DEFAULT (now() at time zone 'utc'), + data jsonb NOT NULL DEFAULT '{}' +); + +ALTER TABLE common_configs + ADD CONSTRAINT "unique_common_configs_uuid" UNIQUE ("uuid"); + + +-- +goose Down + +ALTER TABLE configs + DROP COLUMN uuid; + +ALTER TABLE config_schemas + DROP COLUMN uuid; + +ALTER TABLE modules + DROP COLUMN uuid; + +DROP TABLE common_configs; + diff --git a/model/client.go b/model/client.go new file mode 100644 index 0000000..6096bd5 --- /dev/null +++ b/model/client.go @@ -0,0 +1,22 @@ +package model + +import ( + "github.com/integration-system/isp-lib/database" + log "github.com/integration-system/isp-log" + "github.com/integration-system/isp-log/stdcodes" +) + +var ( + DbClient = database.NewRxDbClient( + database.WithSchemaEnsuring(), + database.WithSchemaAutoInjecting(), + database.WithMigrationsEnsuring(), + database.WithInitializingErrorHandler(func(err *database.ErrorEvent) { + log.Fatal(stdcodes.InitializingDbError, err.Error()) + }), + ) + ConfigRep ConfigRepository = &configRepPg{rxClient: DbClient} + CommonConfigRep CommonConfigRepository = &commonConfigRepPg{rxClient: DbClient} + SchemaRep SchemaRepository = &schemaRepPg{rxClient: DbClient} + ModuleRep ModulesRepository = &modulesRepPg{rxClient: DbClient} +) diff --git a/model/common_config.go b/model/common_config.go new file mode 100644 index 0000000..a62ba44 --- /dev/null +++ b/model/common_config.go @@ -0,0 +1,49 @@ +package model + +import ( + "github.com/go-pg/pg" + "github.com/integration-system/isp-lib/database" + "isp-config-service/entity" +) + +type CommonConfigRepository interface { + Snapshot() ([]entity.CommonConfig, error) + Upsert(config *entity.CommonConfig) (*entity.CommonConfig, error) + Delete(identities []int64) (int, error) +} + +type commonConfigRepPg struct { + rxClient *database.RxDbClient +} + +func (r *commonConfigRepPg) Snapshot() ([]entity.CommonConfig, error) { + var configs []entity.CommonConfig + err := r.rxClient.Visit(func(db *pg.DB) error { + return db.Model(&configs). + Select() + }) + return configs, err +} + +func (r *commonConfigRepPg) Upsert(config *entity.CommonConfig) (*entity.CommonConfig, error) { + err := r.rxClient.Visit(func(db *pg.DB) error { + _, err := db.Model(config). + OnConflict("(id) DO UPDATE"). + Returning("*"). + Insert() + return err + }) + return config, err +} + +func (r *commonConfigRepPg) Delete(identities []int64) (int, error) { + var err error + var res pg.Result + err = r.rxClient.Visit(func(db *pg.DB) error { + res, err = db.Model(&entity.CommonConfig{}). + Where("id IN (?)", pg.In(identities)). + Delete() + return err + }) + return res.RowsAffected(), err +} diff --git a/model/config.go b/model/config.go new file mode 100644 index 0000000..d483423 --- /dev/null +++ b/model/config.go @@ -0,0 +1,49 @@ +package model + +import ( + "github.com/go-pg/pg" + "github.com/integration-system/isp-lib/database" + "isp-config-service/entity" +) + +type ConfigRepository interface { + Snapshot() ([]entity.Config, error) + Upsert(config *entity.Config) (*entity.Config, error) + Delete(identities []int64) (int, error) +} + +type configRepPg struct { + rxClient *database.RxDbClient +} + +func (r *configRepPg) Snapshot() ([]entity.Config, error) { + var configs []entity.Config + err := r.rxClient.Visit(func(db *pg.DB) error { + return db.Model(&configs). + Select() + }) + return configs, err +} + +func (r *configRepPg) Upsert(config *entity.Config) (*entity.Config, error) { + err := r.rxClient.Visit(func(db *pg.DB) error { + _, err := db.Model(config). + OnConflict("(id) DO UPDATE"). + Returning("*"). + Insert() + return err + }) + return config, err +} + +func (r *configRepPg) Delete(identities []int64) (int, error) { + var err error + var res pg.Result + err = r.rxClient.Visit(func(db *pg.DB) error { + res, err = db.Model(&entity.Config{}). + Where("id IN (?)", pg.In(identities)). + Delete() + return err + }) + return res.RowsAffected(), err +} diff --git a/model/module.go b/model/module.go new file mode 100644 index 0000000..bcbd3a9 --- /dev/null +++ b/model/module.go @@ -0,0 +1,48 @@ +package model + +import ( + "github.com/go-pg/pg" + "github.com/integration-system/isp-lib/database" + "isp-config-service/entity" +) + +type ModulesRepository interface { + Snapshot() ([]entity.Module, error) + Upsert(module entity.Module) (entity.Module, error) + Delete(identities []int32) (int, error) +} + +type modulesRepPg struct { + rxClient *database.RxDbClient +} + +func (r *modulesRepPg) Snapshot() ([]entity.Module, error) { + var modules []entity.Module + err := r.rxClient.Visit(func(db *pg.DB) error { + return db.Model(&modules). + Select() + }) + return modules, err +} + +func (r *modulesRepPg) Upsert(module entity.Module) (entity.Module, error) { + err := r.rxClient.Visit(func(db *pg.DB) error { + _, err := db.Model(&module). + OnConflict("(id) DO UPDATE"). + Returning("*"). + Insert() + return err + }) + return module, err +} + +func (r *modulesRepPg) Delete(identities []int32) (int, error) { + var err error + var res pg.Result + err = r.rxClient.Visit(func(db *pg.DB) error { + res, err = db.Model(&entity.Module{}). + Where("id IN (?)", pg.In(identities)).Delete() + return err + }) + return res.RowsAffected(), err +} diff --git a/model/schema.go b/model/schema.go new file mode 100644 index 0000000..85f8218 --- /dev/null +++ b/model/schema.go @@ -0,0 +1,36 @@ +package model + +import ( + "github.com/go-pg/pg" + "github.com/integration-system/isp-lib/database" + "isp-config-service/entity" +) + +type SchemaRepository interface { + Snapshot() ([]entity.ConfigSchema, error) + Upsert(s entity.ConfigSchema) (*entity.ConfigSchema, error) +} + +type schemaRepPg struct { + rxClient *database.RxDbClient +} + +func (r *schemaRepPg) Snapshot() ([]entity.ConfigSchema, error) { + var schemas []entity.ConfigSchema + err := r.rxClient.Visit(func(db *pg.DB) error { + return db.Model(&schemas). + Select() + }) + return schemas, err +} + +func (r *schemaRepPg) Upsert(s entity.ConfigSchema) (*entity.ConfigSchema, error) { + err := r.rxClient.Visit(func(db *pg.DB) error { + _, err := db.Model(&s). + OnConflict("(id) DO UPDATE"). + Returning("*"). + Insert() + return err + }) + return &s, err +} diff --git a/raft/logger.go b/raft/logger.go new file mode 100644 index 0000000..41f0a10 --- /dev/null +++ b/raft/logger.go @@ -0,0 +1,106 @@ +package raft + +import ( + "fmt" + "github.com/hashicorp/go-hclog" + isplog "github.com/integration-system/isp-log" + "github.com/sirupsen/logrus" + "github.com/spf13/cast" + "io" + "isp-config-service/codes" + "log" +) + +type LoggerAdapter struct { + name string +} + +func (l *LoggerAdapter) Log(level logrus.Level, msg string, args ...interface{}) { + if l.name != "" { + msg = fmt.Sprintf("%s:%s", l.name, msg) + } + if len(args) != 0 { + metadata := make(map[string]interface{}, len(args)/2) + for i := 0; i < len(args)-1; i += 2 { + k := cast.ToString(args[i]) + metadata[k] = args[i+1] + } + isplog.WithMetadata(metadata).Log(level, codes.RaftLoggerCode, msg) + + } else { + isplog.Log(level, codes.RaftLoggerCode, msg) + } +} + +func (l *LoggerAdapter) Trace(msg string, args ...interface{}) { + l.Log(logrus.TraceLevel, msg, args) +} + +func (l *LoggerAdapter) Debug(msg string, args ...interface{}) { + l.Log(logrus.DebugLevel, msg, args) +} + +func (l *LoggerAdapter) Info(msg string, args ...interface{}) { + l.Log(logrus.InfoLevel, msg, args) +} + +func (l *LoggerAdapter) Warn(msg string, args ...interface{}) { + l.Log(logrus.WarnLevel, msg, args) +} + +func (l *LoggerAdapter) Error(msg string, args ...interface{}) { + l.Log(logrus.ErrorLevel, msg, args) +} + +func (l *LoggerAdapter) IsTrace() bool { + return isplog.IsLevelEnabled(logrus.TraceLevel) +} + +func (l *LoggerAdapter) IsDebug() bool { + return isplog.IsLevelEnabled(logrus.DebugLevel) +} + +func (l *LoggerAdapter) IsInfo() bool { + return isplog.IsLevelEnabled(logrus.InfoLevel) +} + +func (l *LoggerAdapter) IsWarn() bool { + return isplog.IsLevelEnabled(logrus.WarnLevel) +} + +func (l *LoggerAdapter) IsError() bool { + return isplog.IsLevelEnabled(logrus.ErrorLevel) +} + +// No need to implement that as Raft doesn't use this method. +func (l *LoggerAdapter) With(args ...interface{}) hclog.Logger { + return l +} + +func (l *LoggerAdapter) Named(name string) hclog.Logger { + sl := *l + if sl.name != "" { + sl.name = sl.name + "." + name + } else { + sl.name = name + } + return &sl +} + +func (l *LoggerAdapter) ResetNamed(name string) hclog.Logger { + sl := *l + sl.name = name + return &sl +} + +// Skip +func (l *LoggerAdapter) SetLevel(level hclog.Level) { +} + +func (l *LoggerAdapter) StandardLogger(opts *hclog.StandardLoggerOptions) *log.Logger { + return log.New(isplog.GetOutput(), "", 0) +} + +func (l *LoggerAdapter) StandardWriter(opts *hclog.StandardLoggerOptions) io.Writer { + return isplog.GetOutput() +} diff --git a/raft/manager.go b/raft/manager.go index dbfe61a..02e5b94 100644 --- a/raft/manager.go +++ b/raft/manager.go @@ -99,6 +99,8 @@ func NewRaft(bind string, configuration conf.ClusterConfiguration, state raft.FS } cfg := raft.DefaultConfig() + cfg.Logger = &LoggerAdapter{name: "RAFT"} + cfg.NoSnapshotRestoreOnStart = true cfg.LocalID = raft.ServerID(configuration.OuterAddress) r, err := raft.NewRaft(cfg, state, logStore, store, snapshotStore, trans) if err != nil { diff --git a/service/clusterstate.go b/service/clusterstate.go index 4080821..3af94aa 100644 --- a/service/clusterstate.go +++ b/service/clusterstate.go @@ -1,7 +1,6 @@ package service import ( - "github.com/integration-system/isp-lib/logger" "github.com/integration-system/isp-lib/structure" "isp-config-service/store/state" ) @@ -15,7 +14,6 @@ type clusterStateService struct{} func (l clusterStateService) HandleUpdateBackendDeclarationCommand(declaration structure.BackendDeclaration, state state.State) (state.State, error) { changed := state.UpsertBackend(declaration) if changed { - logger.Debug("HandleUpdateBackendDeclarationCommand: upserted backend", declaration.ModuleName) DiscoveryService.BroadcastModuleAddresses(declaration.ModuleName, state) RoutesService.BroadcastRoutes(state) } @@ -25,7 +23,6 @@ func (l clusterStateService) HandleUpdateBackendDeclarationCommand(declaration s func (l clusterStateService) HandleDeleteBackendDeclarationCommand(declaration structure.BackendDeclaration, state state.State) (state.State, error) { deleted := state.DeleteBackend(declaration) if deleted { - logger.Debug("HandleDeleteBackendDeclarationCommand: deleted backend", declaration.ModuleName) DiscoveryService.BroadcastModuleAddresses(declaration.ModuleName, state) RoutesService.BroadcastRoutes(state) } diff --git a/service/discovery.go b/service/discovery.go index 6eb355d..b07a2a0 100644 --- a/service/discovery.go +++ b/service/discovery.go @@ -3,9 +3,10 @@ package service import ( "encoding/json" "github.com/cenkalti/backoff" - "github.com/integration-system/isp-lib/logger" "github.com/integration-system/isp-lib/structure" "github.com/integration-system/isp-lib/utils" + log "github.com/integration-system/isp-log" + "isp-config-service/codes" "isp-config-service/holder" "isp-config-service/store/state" "isp-config-service/ws" @@ -42,7 +43,10 @@ func (ds *discoveryService) Subscribe(conn ws.Conn, events []string, state state for _, event := range events { addressList := state.GetModuleAddresses(event) event = utils.ModuleConnected(event) - ds.sendAddrList(conn, event, addressList) + err := ds.sendAddrList(conn, event, addressList) + if err != nil { + log.Errorf(codes.DiscoveryServiceError, "send module connected %v", err) + } } } @@ -51,32 +55,37 @@ func (ds *discoveryService) BroadcastModuleAddresses(moduleName string, state st defer ds.lock.RUnlock() event := utils.ModuleConnected(moduleName) addressList := state.GetModuleAddresses(moduleName) - ds.broadcastAddrList(moduleName, event, addressList) -} - -func (ds *discoveryService) broadcastAddrList(moduleName string, event string, addressList []structure.AddressConfiguration) { - if bytes, err := json.Marshal(addressList); err != nil { - logger.Warn(err) - } else { - err = holder.Socket.Broadcast(moduleName, event, string(bytes)) - if err != nil { - logger.Error(err) - } + err := ds.broadcastAddrList(moduleName, event, addressList) + if err != nil { + log.Errorf(codes.DiscoveryServiceError, "broadcast module connected %v", err) } } -func (ds *discoveryService) sendAddrList(conn ws.Conn, event string, addressList []structure.AddressConfiguration) { +func (ds *discoveryService) broadcastAddrList(moduleName string, event string, addressList []structure.AddressConfiguration) error { if bytes, err := json.Marshal(addressList); err != nil { - logger.Warn(err) + return err + } else { + err = holder.Socket.Broadcast(moduleName, event, string(bytes)) + if err != nil { + return err + } + } + return nil +} + +func (ds *discoveryService) sendAddrList(conn ws.Conn, event string, addressList []structure.AddressConfiguration) error { + if bytes, err := json.Marshal(addressList); err != nil { + return err } else { bf := backoff.WithMaxRetries(backoff.NewConstantBackOff(100*time.Millisecond), 3) err := backoff.Retry(func() error { return conn.Emit(event, string(bytes)) }, bf) if err != nil { - logger.Error(err) + return err } } + return nil } func NewDiscoveryService() *discoveryService { diff --git a/service/routes.go b/service/routes.go index 6660849..887db98 100644 --- a/service/routes.go +++ b/service/routes.go @@ -3,9 +3,10 @@ package service import ( "encoding/json" "github.com/cenkalti/backoff" - "github.com/integration-system/isp-lib/logger" "github.com/integration-system/isp-lib/structure" "github.com/integration-system/isp-lib/utils" + log "github.com/integration-system/isp-log" + "isp-config-service/codes" "isp-config-service/holder" "isp-config-service/store/state" "isp-config-service/ws" @@ -27,35 +28,45 @@ func (rs *routesService) HandleDisconnect(connId string) { func (rs *routesService) SubscribeRoutes(conn ws.Conn, state state.ReadState) { holder.Socket.Rooms().Join(conn, RoutesSubscribersRoom) routes := state.GetRoutes() - rs.sendRoutes(conn, utils.ConfigSendRoutesWhenConnected, routes) + err := rs.sendRoutes(conn, utils.ConfigSendRoutesWhenConnected, routes) + if err != nil { + log.Errorf(codes.RoutesServiceError, "send routes %v", err) + } + } func (rs *routesService) BroadcastRoutes(state state.ReadState) { routes := state.GetRoutes() - rs.broadcastRoutes(utils.ConfigSendRoutesChanged, routes) + err := rs.broadcastRoutes(utils.ConfigSendRoutesChanged, routes) + if err != nil { + log.Errorf(codes.RoutesServiceError, "broadcast routes %v", err) + } + } -func (rs *routesService) broadcastRoutes(event string, routes structure.RoutingConfig) { +func (rs *routesService) broadcastRoutes(event string, routes structure.RoutingConfig) error { if bytes, err := json.Marshal(routes); err != nil { - logger.Warn(err) + return err } else { err = holder.Socket.Broadcast(RoutesSubscribersRoom, event, string(bytes)) if err != nil { - logger.Error(err) + return err } } + return nil } -func (rs *routesService) sendRoutes(conn ws.Conn, event string, routes structure.RoutingConfig) { +func (rs *routesService) sendRoutes(conn ws.Conn, event string, routes structure.RoutingConfig) error { if bytes, err := json.Marshal(routes); err != nil { - logger.Warn(err) + return err } else { bf := backoff.WithMaxRetries(backoff.NewConstantBackOff(100*time.Millisecond), 3) err := backoff.Retry(func() error { return conn.Emit(event, string(bytes)) }, bf) if err != nil { - logger.Error(err) + return err } } + return nil } diff --git a/store/apply.go b/store/apply.go index 00b88f7..c143fb3 100644 --- a/store/apply.go +++ b/store/apply.go @@ -1,7 +1,7 @@ package store import ( - "github.com/integration-system/isp-lib/logger" + "fmt" "github.com/integration-system/isp-lib/structure" "isp-config-service/service" ) @@ -10,12 +10,11 @@ func (s *Store) applyUpdateBackendDeclarationCommand(data []byte) error { declaration := structure.BackendDeclaration{} err := json.Unmarshal(data, &declaration) if err != nil { - logger.Warnf("Store.applyUpdateBackendDeclarationCommand: %s, error parse json data: %s", err.Error()) - return err + return fmt.Errorf("UpdateBackendDeclarationCommand: %w", err) } state, err := service.ClusterStateService.HandleUpdateBackendDeclarationCommand(declaration, s.state) if err != nil { - return err + return fmt.Errorf("UpdateBackendDeclarationCommand: %w", err) } s.state = state return nil @@ -25,8 +24,7 @@ func (s *Store) applyDeleteBackendDeclarationCommand(data []byte) error { declaration := structure.BackendDeclaration{} err := json.Unmarshal(data, &declaration) if err != nil { - logger.Warnf("Store.applyDeleteBackendDeclarationCommand: %s, error parse json data: %s", err.Error()) - return err + return fmt.Errorf("DeleteBackendDeclarationCommand: %w", err) } state, err := service.ClusterStateService.HandleDeleteBackendDeclarationCommand(declaration, s.state) if err != nil { diff --git a/store/restore.go b/store/restore.go new file mode 100644 index 0000000..33ee981 --- /dev/null +++ b/store/restore.go @@ -0,0 +1,38 @@ +package store + +import ( + log "github.com/integration-system/isp-log" + "isp-config-service/cluster" + "isp-config-service/codes" + "isp-config-service/model" + "isp-config-service/store/state" +) + +func NewStateStoreFromRepository() *Store { + configs, err := model.ConfigRep.Snapshot() + if err != nil { + log.Fatalf(codes.RestoreFromRepositoryError, "config repository: %s", err) + } + schemas, err := model.SchemaRep.Snapshot() + if err != nil { + log.Fatalf(codes.RestoreFromRepositoryError, "schema repository: %s", err) + } + modules, err := model.ModuleRep.Snapshot() + if err != nil { + log.Fatalf(codes.RestoreFromRepositoryError, "module repository: %s", err) + } + commonConfigs, err := model.CommonConfigRep.Snapshot() + if err != nil { + log.Fatalf(codes.RestoreFromRepositoryError, "module repository: %s", err) + } + + store := &Store{ + state: state.NewStateFromSnapshot(configs, schemas, modules, commonConfigs), + } + + store.handlers = map[uint64]func([]byte) error{ + cluster.UpdateBackendDeclarationCommand: store.applyUpdateBackendDeclarationCommand, + cluster.DeleteBackendDeclarationCommand: store.applyDeleteBackendDeclarationCommand, + } + return store +} diff --git a/store/state/common_config.go b/store/state/common_config.go new file mode 100644 index 0000000..9256d16 --- /dev/null +++ b/store/state/common_config.go @@ -0,0 +1,24 @@ +package state + +import "isp-config-service/entity" + +type CommonConfigStore struct { + configs []entity.CommonConfig +} + +func (cs *CommonConfigStore) Upsert(config entity.CommonConfig) { + // TODO +} + +func (cs *CommonConfigStore) Delete(config entity.CommonConfig) { + // TODO +} + +func (cs *CommonConfigStore) GetById(id int64) (*entity.CommonConfig, error) { + // TODO + return nil, nil +} + +func NewCommonConfigStore() *CommonConfigStore { + return &CommonConfigStore{configs: make([]entity.CommonConfig, 0)} +} diff --git a/store/state/configs.go b/store/state/configs.go new file mode 100644 index 0000000..42c0e9d --- /dev/null +++ b/store/state/configs.go @@ -0,0 +1,33 @@ +package state + +import "isp-config-service/entity" + +type ConfigStore struct { + configs []entity.Config +} + +func (cs *ConfigStore) Upsert(config entity.Config) { + // TODO +} + +func (cs *ConfigStore) Delete(config entity.Config) { + // TODO +} + +func (cs *ConfigStore) Activate(config entity.Config) { + // TODO +} + +func (cs *ConfigStore) GetByModuleName(moduleName string) (*entity.Config, error) { + // TODO + return nil, nil +} + +func (cs *ConfigStore) GetById(id int64) (*entity.Config, error) { + // TODO + return nil, nil +} + +func NewConfigStore() *ConfigStore { + return &ConfigStore{configs: make([]entity.Config, 0)} +} diff --git a/store/state/modules.go b/store/state/modules.go new file mode 100644 index 0000000..c51e6a5 --- /dev/null +++ b/store/state/modules.go @@ -0,0 +1,30 @@ +package state + +import "isp-config-service/entity" + +type ModuleStore struct { + modules []entity.Module +} + +func (ms *ModuleStore) Upsert(module entity.Module) { + // TODO +} + +func (ms *ModuleStore) GetByName(name string) (*entity.Module, error) { + // TODO + return nil, nil +} + +func (ms *ModuleStore) GetById(id int32) (*entity.Module, error) { + // TODO + return nil, nil +} + +func (ms *ModuleStore) GetActiveModules() ([]entity.Module, error) { + // TODO + return nil, nil +} + +func NewModuleStore() *ModuleStore { + return &ModuleStore{modules: make([]entity.Module, 0)} +} diff --git a/store/state/schemas.go b/store/state/schemas.go new file mode 100644 index 0000000..b2fa27b --- /dev/null +++ b/store/state/schemas.go @@ -0,0 +1,25 @@ +package state + +import "isp-config-service/entity" + +type SchemaStore struct { + schemas []entity.ConfigSchema +} + +func (ss *SchemaStore) Upsert(schema entity.ConfigSchema) { + // TODO +} + +func (ss *SchemaStore) GetByModuleId(moduleId int32) (*entity.ConfigSchema, error) { + // TODO + return nil, nil +} + +func (ss *SchemaStore) GetById(id int64) (*entity.ConfigSchema, error) { + // TODO + return nil, nil +} + +func NewSchemaStore() *SchemaStore { + return &SchemaStore{schemas: make([]entity.ConfigSchema, 0)} +} diff --git a/store/state/state.go b/store/state/state.go index e6a577e..4f335ae 100644 --- a/store/state/state.go +++ b/store/state/state.go @@ -2,10 +2,15 @@ package state import ( "github.com/integration-system/isp-lib/structure" + "isp-config-service/entity" ) type State struct { - mesh *Mesh + mesh *Mesh + configs *ConfigStore + schemas *SchemaStore + modules *ModuleStore + commonConfigs *CommonConfigStore } type ReadState interface { @@ -17,7 +22,21 @@ type ReadState interface { func NewState() State { return State{ - mesh: NewMesh(), + mesh: NewMesh(), + configs: NewConfigStore(), + schemas: NewSchemaStore(), + modules: NewModuleStore(), + commonConfigs: NewCommonConfigStore(), + } +} + +func NewStateFromSnapshot(configs []entity.Config, schemas []entity.ConfigSchema, modules []entity.Module, commConfigs []entity.CommonConfig) State { + return State{ + mesh: NewMesh(), + configs: &ConfigStore{configs: configs}, + schemas: &SchemaStore{schemas: schemas}, + modules: &ModuleStore{modules: modules}, + commonConfigs: &CommonConfigStore{configs: commConfigs}, } } diff --git a/store/store.go b/store/store.go index 20154da..67a71e0 100644 --- a/store/store.go +++ b/store/store.go @@ -3,12 +3,13 @@ package store import ( "encoding/binary" "github.com/hashicorp/raft" - "github.com/integration-system/isp-lib/logger" + 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" ) @@ -24,40 +25,36 @@ type Store struct { } func (s *Store) Apply(l *raft.Log) interface{} { - logger.Debug("Applying...") s.lock.Lock() defer s.lock.Unlock() if len(l.Data) < 8 { - logger.Fatal("Invalid log data command", l.Data) + log.Fatalf(codes.InvalidLogDataCommand, "invalid log data command: %s", l.Data) } command := binary.BigEndian.Uint64(l.Data[:8]) if handler, ok := s.handlers[command]; ok { err := handler(l.Data[8:]) if err != nil { - logger.Fatal("error while applying log command", command, err) + log.Fatalf(codes.ApplyLogCommandError, "apply log command: %v", err) } } else { - logger.Fatal("Log command not found", command) + log.Fatalf(codes.UnknownLogCommand, "unknown log command %s", command) } return nil } func (s *Store) Snapshot() (raft.FSMSnapshot, error) { s.lock.Lock() - defer s.lock.Unlock() - logger.Debug("Create snapshot") - copied := deepcopy.Copy(s.state).(state.State) + s.lock.Unlock() return &fsmSnapshot{copied}, nil } func (s *Store) Restore(rc io.ReadCloser) error { - state := state.State{} - logger.Debug("Try to restore snapshot") - if err := json.NewDecoder(rc).Decode(&state); err != nil { + state2 := state.State{} + if err := json.NewDecoder(rc).Decode(&state2); err != nil { return errors.WithMessage(err, "unmarshal store") } - s.state = state + s.state = state2 return nil } diff --git a/subs/client.go b/subs/client.go index 41c3168..2f547ca 100644 --- a/subs/client.go +++ b/subs/client.go @@ -4,9 +4,10 @@ import ( "encoding/json" "github.com/asaskevich/govalidator" "github.com/integration-system/isp-lib/bootstrap" - "github.com/integration-system/isp-lib/logger" "github.com/integration-system/isp-lib/structure" + log "github.com/integration-system/isp-log" "isp-config-service/cluster" + "isp-config-service/codes" "isp-config-service/service" "isp-config-service/store/state" "isp-config-service/ws" @@ -16,14 +17,11 @@ func (h *socketEventHandler) handleModuleReady(conn ws.Conn, data []byte) string declaration := structure.BackendDeclaration{} err := json.Unmarshal(data, &declaration) if err != nil { - logger.Warnf("handleModuleDeclaration: %s, error parse json data: %s", conn.Id(), err.Error()) return err.Error() } _, err = govalidator.ValidateStruct(declaration) if err != nil { - errors := govalidator.ErrorsByField(err) - logger.Warnf("SOCKET ROUTES ERROR, handleModuleDeclaration: %s, error validate routes data: %s", conn.Id(), errors) return err.Error() } conn.SetBackendDeclaration(declaration) @@ -34,16 +32,19 @@ func (h *socketEventHandler) handleModuleReady(conn ws.Conn, data []byte) string if changed { command := cluster.PrepareUpdateBackendDeclarationCommand(declaration) i, err := h.cluster.SyncApply(command) - logger.Debug("cluster.SyncApply UpdateBackendDeclarationCommand:", i, err) + if err != nil { + log.WithMetadata(map[string]interface{}{ + "answer": i, + }).Warnf(codes.SyncApplyError, "apply UpdateBackendDeclarationCommand %v", err) + } } return Ok } func (h *socketEventHandler) handleModuleRequirements(conn ws.Conn, data []byte) string { - logger.Debugf("onReceivedModuleRequirements: %s %s", conn.Id(), string(data)) - instanceUuid, moduleName, err := conn.Parameters() - logger.Debug("instanceUuid:", instanceUuid, "moduleName:", moduleName) // REMOVE + moduleName, err := conn.Parameters() + log.Debugf(0, "handleModuleRequirements moduleName: %s", moduleName) // REMOVE if err != nil { return err.Error() } @@ -51,7 +52,6 @@ func (h *socketEventHandler) handleModuleRequirements(conn ws.Conn, data []byte) declaration := bootstrap.ModuleRequirements{} err = json.Unmarshal(data, &declaration) if err != nil { - logger.Debugf("onReceivedModuleRequirements: %s, error parse json data: %s", conn.Id(), err.Error()) return err.Error() } diff --git a/subs/root.go b/subs/root.go index 841b553..dd7a5bd 100644 --- a/subs/root.go +++ b/subs/root.go @@ -1,9 +1,10 @@ package subs import ( - "github.com/integration-system/isp-lib/logger" "github.com/integration-system/isp-lib/utils" + log "github.com/integration-system/isp-log" "isp-config-service/cluster" + "isp-config-service/codes" "isp-config-service/holder" "isp-config-service/service" "isp-config-service/store" @@ -11,8 +12,7 @@ import ( ) const ( - Ok = "ok" - + Ok = "ok" followersRoom = "followers" ) @@ -50,12 +50,16 @@ func (h *socketEventHandler) handleDisconnect(conn ws.Conn) { if backend != nil { command := cluster.PrepareDeleteBackendDeclarationCommand(*backend) i, err := h.cluster.SyncApply(command) - logger.Debug("cluster.SyncApply DeleteBackendDeclarationCommand:", i, err) + if err != nil { + log.WithMetadata(map[string]interface{}{ + "answer": i, + }).Warnf(codes.SyncApplyError, "apply DeleteBackendDeclarationCommand %v", err) + } } } func (h *socketEventHandler) handleError(conn ws.Conn, err error) { - logger.Warnf("socket.io: %v", err) + log.Warnf(codes.SocketIoError, "socket.io: %v", err) } func NewSocketEventHandler(socket *ws.WebsocketServer, cluster *cluster.ClusterClient, store *store.Store) *socketEventHandler { diff --git a/ws/conn.go b/ws/conn.go index f3b06b6..9b8e90f 100644 --- a/ws/conn.go +++ b/ws/conn.go @@ -9,7 +9,7 @@ import ( type Conn interface { Id() string - Parameters() (instanceUUID string, moduleName string, error error) + Parameters() (moduleName string, err error) Emit(event string, args ...interface{}) error IsConfigClusterNode() bool SetBackendDeclaration(backend structure.BackendDeclaration) @@ -21,8 +21,10 @@ type wsConn struct { backend *structure.BackendDeclaration } -func (c *wsConn) Parameters() (instanceUUID string, moduleName string, error error) { - return utils.ParseParameters(c.conn.Request().URL.RawQuery) +func (c *wsConn) Parameters() (moduleName string, err error) { + // TODO remove instanceUUID from isp-lib + _, moduleName, err = utils.ParseParameters(c.conn.Request().URL.RawQuery) + return moduleName, err } func (c *wsConn) Id() string {