reformat state access and errors handling
This commit is contained in:
1 parent
b1a0bc252f
commit
c31abb84c9
29 files changed
+451
-448
No files matched your search
@@ -1,92 +0,0 @@
|
||||
## Contents
|
||||
## [1. Installing](#installing)
|
||||
## [2. Using](#using)
|
||||
## [3. Environment variables](#environment-variables)
|
||||
|
||||
|
||||
|
||||
|
||||
## Installing
|
||||
### 1. Download dependencies
|
||||
```
|
||||
go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway
|
||||
go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger
|
||||
go get -u github.com/golang/protobuf/protoc-gen-go
|
||||
```
|
||||
### 2. Generate GRPC, GRPC-gateway, GRPC-gateway-swagger
|
||||
###### WINDOWS
|
||||
```cmd
|
||||
protoc ^
|
||||
-I. -I%GOPATH%\src ^
|
||||
-I%GOPATH%\src\github.com\grpc-ecosystem\grpc-gateway\third_party\googleapis ^
|
||||
--go_out=plugins=grpc:. --grpc-gateway_out=logtostderr=true:. --swagger_out=logtostderr=true:. ^
|
||||
proto\config_service.proto
|
||||
```
|
||||
###### LINUX
|
||||
```bash
|
||||
protoc -I. \
|
||||
-I$GOPATH \
|
||||
-I$GOPATH/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
|
||||
--go_out=plugins=grpc:. --grpc-gateway_out=logtostderr=true:. --swagger_out=logtostderr=true:. \
|
||||
proto/config_service.proto
|
||||
```
|
||||
|
||||
## Using
|
||||
### 1. GRPC
|
||||
Default GRPC port is: `5001`, might be changed in config file
|
||||
Proto file is: `proto/config_service.proto`
|
||||
### 2. REST proxy to GRPC
|
||||
Default port is: `5000`, might be changed in config file
|
||||
Swagger work on http://0.0.0.0:5000/swagger
|
||||
### 3. SocketIO
|
||||
For connect to this server two variables must be sent in query path:
|
||||
1. `module_name` - Module name, for example `auth`.
|
||||
2. `instance_uuid` - UUID - instance identity.
|
||||
|
||||
#### Events
|
||||
##### Event to a client
|
||||
`CONFIG:SEND_CONFIG_WHEN_CONNECTED` - When a connection is established to a client will send an event.
|
||||
|
||||
`CONFIG:SEND_CONFIG_CHANGED` - When config for particular module had been changed this event with new config will send to a client.
|
||||
|
||||
`CONFIG:SEND_CONFIG_ON_REQUEST` - the server will send to a client actual config with this event after `CONFIG:REQUEST_CONFIG`
|
||||
|
||||
###### The next events work on both sides. First, when new backend publishes new methods at config service there is incoming one of this events:
|
||||
|
||||
`ROUTES:SEND_ROUTES_WHEN_CONNECTED` - A backend sends this event when a connection is established with a config server.
|
||||
|
||||
`ROUTES:SEND_ROUTES_CHANGED` - Any module can say that something had changed in its methods.
|
||||
|
||||
`ROUTES:SEND_ROUTES_ON_REQUEST` - A config service is able to make a request to renew list methods.
|
||||
|
||||
###### A config service, in turn, send the same events types in each its connection.
|
||||
|
||||
For all of this events we wait for next data structure:
|
||||
```json
|
||||
{
|
||||
"address": {
|
||||
"ip": "10.10.10.10",
|
||||
"port": "5001"
|
||||
},
|
||||
"endpoints": [
|
||||
{"path": "/api/user/get"},
|
||||
{"path": "/api/user/save"},
|
||||
{"path": "/api/user/delete"}
|
||||
]
|
||||
}
|
||||
```
|
||||
##### Event to the server
|
||||
`CONFIG:REQUEST_CONFIG` - A client can request current config with this event.
|
||||
|
||||
## Environment variables
|
||||
`APP_PROFILE` - Name for config file, default is `config`. Will seek file with name: `config.yml`.
|
||||
|
||||
`APP_CONFIG_PATH` - Absolute path where a config file is. If a variable hadn't been specified config will seek into the same directory, when binary file placed.
|
||||
|
||||
`LOG_LEVEL` - Log level, the default is `INFO`.
|
||||
|
||||
`APP_MODE` - If set to `dev` logger for SQL will be on and if `LOG_LEVEL` hadn't been specified it will set to `DEBUG`.
|
||||
|
||||
## Changes
|
||||
#### 0.2.2 - 2018-10-05
|
||||
- Add default config for mdm module
|
||||
+9
-9
@@ -24,7 +24,7 @@ const (
|
||||
defaultApplyTimeout = 3 * time.Second
|
||||
)
|
||||
|
||||
type ClusterClient struct {
|
||||
type Client struct {
|
||||
r *raft.Raft
|
||||
|
||||
leaderMu sync.RWMutex
|
||||
@@ -34,7 +34,7 @@ type ClusterClient struct {
|
||||
onClientDisconnect func(string)
|
||||
}
|
||||
|
||||
func (client *ClusterClient) Shutdown() error {
|
||||
func (client *Client) Shutdown() error {
|
||||
client.leaderMu.Lock()
|
||||
defer client.leaderMu.Unlock()
|
||||
|
||||
@@ -46,14 +46,14 @@ func (client *ClusterClient) Shutdown() error {
|
||||
return client.r.GracefulShutdown()
|
||||
}
|
||||
|
||||
func (client *ClusterClient) IsLeader() bool {
|
||||
func (client *Client) IsLeader() bool {
|
||||
client.leaderMu.RLock()
|
||||
defer client.leaderMu.RUnlock()
|
||||
|
||||
return client.leaderState.isLeader
|
||||
}
|
||||
|
||||
func (client *ClusterClient) SyncApply(command []byte) (*ApplyLogResponse, error) {
|
||||
func (client *Client) SyncApply(command []byte) (*ApplyLogResponse, error) {
|
||||
client.leaderMu.RLock()
|
||||
defer client.leaderMu.RUnlock()
|
||||
|
||||
@@ -85,7 +85,7 @@ func (client *ClusterClient) SyncApply(command []byte) (*ApplyLogResponse, error
|
||||
}
|
||||
}
|
||||
|
||||
func (client *ClusterClient) SyncApplyOnLeader(command []byte) (*ApplyLogResponse, error) {
|
||||
func (client *Client) SyncApplyOnLeader(command []byte) (*ApplyLogResponse, error) {
|
||||
client.leaderMu.RLock()
|
||||
defer client.leaderMu.RUnlock()
|
||||
|
||||
@@ -100,7 +100,7 @@ func (client *ClusterClient) SyncApplyOnLeader(command []byte) (*ApplyLogRespons
|
||||
return &logResponse, err
|
||||
}
|
||||
|
||||
func (client *ClusterClient) listenLeader() {
|
||||
func (client *Client) listenLeader() {
|
||||
for n := range client.r.LeaderCh() {
|
||||
client.leaderMu.Lock()
|
||||
if client.leaderState.leaderAddr != n.CurrentLeaderAddress {
|
||||
@@ -140,7 +140,7 @@ func (client *ClusterClient) listenLeader() {
|
||||
}
|
||||
if applyLogResponse != nil && applyLogResponse.ApplyError != "" {
|
||||
log.WithMetadata(map[string]interface{}{
|
||||
"comment": applyLogResponse.Comment,
|
||||
"comment": applyLogResponse.Result,
|
||||
"applyError": applyLogResponse.ApplyError,
|
||||
}).Warn(codes.SyncApplyError, "cluster.SyncApply announce myself")
|
||||
}
|
||||
@@ -162,8 +162,8 @@ type leaderState struct {
|
||||
leaderAddr string
|
||||
}
|
||||
|
||||
func NewRaftClusterClient(r *raft.Raft, declaration structure.BackendDeclaration, onLeaderDisconnect func(string)) *ClusterClient {
|
||||
client := &ClusterClient{
|
||||
func NewRaftClusterClient(r *raft.Raft, declaration structure.BackendDeclaration, onLeaderDisconnect func(string)) *Client {
|
||||
client := &Client{
|
||||
r: r,
|
||||
declaration: declaration,
|
||||
leaderState: leaderState{},
|
||||
|
||||
+3
-1
@@ -1,12 +1,14 @@
|
||||
package cluster
|
||||
|
||||
import json2 "encoding/json"
|
||||
|
||||
type ModuleConnected struct {
|
||||
ModuleName string
|
||||
}
|
||||
|
||||
type ApplyLogResponse struct {
|
||||
ApplyError string
|
||||
Comment string
|
||||
Result json2.RawMessage
|
||||
}
|
||||
|
||||
func (a ApplyLogResponse) Error() string {
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
ClusterClient *cluster.ClusterClient
|
||||
ClusterClient *cluster.Client
|
||||
Socket *ws.WebsocketServer
|
||||
HttpServer *http.Server
|
||||
)
|
||||
@@ -66,7 +66,7 @@ func main() {
|
||||
<-shutdownChan
|
||||
}
|
||||
|
||||
func initWebsocket(bindAddress string, clusterClient *cluster.ClusterClient, raftStore *store.Store) {
|
||||
func initWebsocket(bindAddress string, clusterClient *cluster.Client, raftStore *store.Store) {
|
||||
socket, err := ws.NewWebsocketServer()
|
||||
if err != nil {
|
||||
// TODO уйдет при миграции
|
||||
@@ -86,15 +86,20 @@ func initWebsocket(bindAddress string, clusterClient *cluster.ClusterClient, raf
|
||||
holder.HttpServer = httpServer
|
||||
}
|
||||
|
||||
func initRaft(bindAddress string, clusterCfg conf.ClusterConfiguration, declaration structure.BackendDeclaration) (*cluster.ClusterClient, *store.Store) {
|
||||
raftState := store.NewStateFromRepository()
|
||||
func initRaft(bindAddress string, clusterCfg conf.ClusterConfiguration, declaration structure.BackendDeclaration) (*cluster.Client, *store.Store) {
|
||||
raftState, err := store.NewStateFromRepository()
|
||||
if err != nil {
|
||||
log.Fatal(codes.RestoreFromRepositoryError, err)
|
||||
return nil, nil
|
||||
}
|
||||
raftStore := store.NewStateStore(raftState)
|
||||
r, err := raft.NewRaft(bindAddress, clusterCfg, raftStore)
|
||||
if err != nil {
|
||||
log.Fatalf(codes.InitRaftError, "unable to create raft server. %v", err)
|
||||
return nil, nil
|
||||
}
|
||||
clusterClient := cluster.NewRaftClusterClient(r, declaration, func(address string) {
|
||||
raftStore.VisitState(func(s state.State) {
|
||||
raftStore.VisitState(func(s state.WritableState) {
|
||||
cfg := config.Get().(*conf.Configuration)
|
||||
addr, err := net.ResolveTCPAddr("tcp", address)
|
||||
if err != nil {
|
||||
@@ -114,7 +119,7 @@ func initRaft(bindAddress string, clusterCfg conf.ClusterConfiguration, declarat
|
||||
//
|
||||
addressConfiguration := structure.AddressConfiguration{Port: strconv.Itoa(port), IP: addr.IP.String()}
|
||||
back := structure.BackendDeclaration{ModuleName: cfg.ModuleName, Address: addressConfiguration}
|
||||
_, err = service.ClusterStateService.HandleDeleteBackendDeclarationCommand(back, s)
|
||||
err = service.ClusterMeshService.HandleDeleteBackendDeclarationCommand(back, s)
|
||||
if err != nil {
|
||||
log.Warnf(codes.DeleteBackendDeclarationError, "onClientDisconnect delete backend declaration. %v", err)
|
||||
}
|
||||
|
||||
@@ -17,10 +17,9 @@ type commonConfigRepPg struct {
|
||||
}
|
||||
|
||||
func (r *commonConfigRepPg) Snapshot() ([]entity.CommonConfig, error) {
|
||||
var configs []entity.CommonConfig
|
||||
configs := make([]entity.CommonConfig, 0)
|
||||
err := r.rxClient.Visit(func(db *pg.DB) error {
|
||||
return db.Model(&configs).
|
||||
Select()
|
||||
return db.Model(&configs).Select()
|
||||
})
|
||||
return configs, err
|
||||
}
|
||||
|
||||
+2
-3
@@ -17,10 +17,9 @@ type configRepPg struct {
|
||||
}
|
||||
|
||||
func (r *configRepPg) Snapshot() ([]entity.Config, error) {
|
||||
var configs []entity.Config
|
||||
configs := make([]entity.Config, 0)
|
||||
err := r.rxClient.Visit(func(db *pg.DB) error {
|
||||
return db.Model(&configs).
|
||||
Select()
|
||||
return db.Model(&configs).Select()
|
||||
})
|
||||
return configs, err
|
||||
}
|
||||
|
||||
+2
-3
@@ -17,10 +17,9 @@ type modulesRepPg struct {
|
||||
}
|
||||
|
||||
func (r *modulesRepPg) Snapshot() ([]entity.Module, error) {
|
||||
var modules []entity.Module
|
||||
modules := make([]entity.Module, 0)
|
||||
err := r.rxClient.Visit(func(db *pg.DB) error {
|
||||
return db.Model(&modules).
|
||||
Select()
|
||||
return db.Model(&modules).Select()
|
||||
})
|
||||
return modules, err
|
||||
}
|
||||
|
||||
+2
-3
@@ -16,10 +16,9 @@ type schemaRepPg struct {
|
||||
}
|
||||
|
||||
func (r *schemaRepPg) Snapshot() ([]entity.ConfigSchema, error) {
|
||||
var schemas []entity.ConfigSchema
|
||||
schemas := make([]entity.ConfigSchema, 0)
|
||||
err := r.rxClient.Visit(func(db *pg.DB) error {
|
||||
return db.Model(&schemas).
|
||||
Select()
|
||||
return db.Model(&schemas).Select()
|
||||
})
|
||||
return schemas, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"github.com/integration-system/isp-lib/structure"
|
||||
log "github.com/integration-system/isp-log"
|
||||
"isp-config-service/codes"
|
||||
"isp-config-service/holder"
|
||||
"isp-config-service/model"
|
||||
"isp-config-service/store/state"
|
||||
)
|
||||
|
||||
var (
|
||||
ClusterMeshService clusterMeshService
|
||||
)
|
||||
|
||||
type clusterMeshService struct{}
|
||||
|
||||
func (clusterMeshService) HandleUpdateBackendDeclarationCommand(declaration structure.BackendDeclaration, state state.WritableState) error {
|
||||
changed := state.WritableMesh().UpsertBackend(declaration)
|
||||
if changed {
|
||||
DiscoveryService.BroadcastModuleAddresses(declaration.ModuleName, state)
|
||||
RoutesService.BroadcastRoutes(state)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (clusterMeshService) HandleDeleteBackendDeclarationCommand(declaration structure.BackendDeclaration, state state.WritableState) error {
|
||||
deleted := state.WritableMesh().DeleteBackend(declaration)
|
||||
if deleted {
|
||||
DiscoveryService.BroadcastModuleAddresses(declaration.ModuleName, state)
|
||||
RoutesService.BroadcastRoutes(state)
|
||||
module := ModuleRegistryService.updateModuleLastDisconnected(declaration.ModuleName, state.WritableModules())
|
||||
if holder.ClusterClient.IsLeader() {
|
||||
_, err := model.ModuleRep.Upsert(module)
|
||||
if err != nil {
|
||||
log.Errorf(codes.DatabaseOperationError, "upsert module: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"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/holder"
|
||||
"isp-config-service/model"
|
||||
"isp-config-service/store/state"
|
||||
)
|
||||
|
||||
var (
|
||||
ClusterStateService clusterStateService
|
||||
)
|
||||
|
||||
type clusterStateService struct{}
|
||||
|
||||
func (clusterStateService) HandleUpdateBackendDeclarationCommand(declaration structure.BackendDeclaration, state state.State) (state.State, error) {
|
||||
changed := state.UpsertBackend(declaration)
|
||||
if changed {
|
||||
DiscoveryService.BroadcastModuleAddresses(declaration.ModuleName, state)
|
||||
RoutesService.BroadcastRoutes(state)
|
||||
}
|
||||
return state, nil
|
||||
}
|
||||
|
||||
func (clusterStateService) HandleDeleteBackendDeclarationCommand(declaration structure.BackendDeclaration, state state.State) (state.State, error) {
|
||||
deleted := state.DeleteBackend(declaration)
|
||||
if deleted {
|
||||
DiscoveryService.BroadcastModuleAddresses(declaration.ModuleName, state)
|
||||
RoutesService.BroadcastRoutes(state)
|
||||
module := state.UpdateModuleLastDisconnected(declaration.ModuleName)
|
||||
if holder.ClusterClient.IsLeader() {
|
||||
_, err := model.ModuleRep.Upsert(module)
|
||||
if err != nil {
|
||||
log.Errorf(codes.DatabaseOperationError, "upsert module: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return state, nil
|
||||
}
|
||||
|
||||
func (clusterStateService) HandleModuleConnectedCommand(moduleConnected cluster.ModuleConnected, state state.State) (state.State, error) {
|
||||
module := state.UpdateModuleLastConnected(moduleConnected.ModuleName)
|
||||
if holder.ClusterClient.IsLeader() {
|
||||
_, err := model.ModuleRep.Upsert(module)
|
||||
if err != nil {
|
||||
log.Errorf(codes.DatabaseOperationError, "upsert module: %v", err)
|
||||
}
|
||||
}
|
||||
return state, nil
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"github.com/integration-system/bellows"
|
||||
"github.com/pkg/errors"
|
||||
"isp-config-service/store/state"
|
||||
)
|
||||
|
||||
var (
|
||||
ConfigService = configService{}
|
||||
)
|
||||
|
||||
type configService struct{}
|
||||
|
||||
func (configService) GetCompiledConfig(moduleName string, state state.ReadonlyState) (map[string]interface{}, error) {
|
||||
module := state.Modules().GetByName(moduleName)
|
||||
if module == nil {
|
||||
return nil, errors.Errorf("module with name %s not found", moduleName)
|
||||
}
|
||||
config := state.Configs().GetActiveByModuleId(module.Id)
|
||||
if config == nil {
|
||||
return nil, errors.Errorf("no active configs for moduleId %s", module.Id)
|
||||
}
|
||||
commonConfigs := state.CommonConfigs().GetByIds(config.CommonConfigs)
|
||||
configsToMerge := make([]map[string]interface{}, 0, len(commonConfigs))
|
||||
for _, common := range commonConfigs {
|
||||
configsToMerge = append(configsToMerge, common.Data)
|
||||
}
|
||||
configsToMerge = append(configsToMerge, config.Data)
|
||||
|
||||
resultData := mergeNestedMaps(configsToMerge...)
|
||||
return resultData, nil
|
||||
}
|
||||
|
||||
func mergeNestedMaps(maps ...map[string]interface{}) map[string]interface{} {
|
||||
if len(maps) == 1 {
|
||||
return maps[0]
|
||||
}
|
||||
result := bellows.Flatten(maps[0])
|
||||
for i := 1; i < len(maps); i++ {
|
||||
newFlatten := bellows.Flatten(maps[i])
|
||||
for k, v := range newFlatten {
|
||||
result[k] = v
|
||||
}
|
||||
}
|
||||
return bellows.Expand(result).(map[string]interface{})
|
||||
}
|
||||
@@ -32,7 +32,7 @@ func (ds *discoveryService) HandleDisconnect(connId string) {
|
||||
}
|
||||
}
|
||||
|
||||
func (ds *discoveryService) Subscribe(conn ws.Conn, events []string, state state.ReadState) {
|
||||
func (ds *discoveryService) Subscribe(conn ws.Conn, events []string, state state.ReadonlyState) {
|
||||
if len(events) == 0 {
|
||||
return
|
||||
}
|
||||
@@ -41,7 +41,7 @@ func (ds *discoveryService) Subscribe(conn ws.Conn, events []string, state state
|
||||
ds.subs[conn.Id()] = events
|
||||
holder.Socket.Rooms().Join(conn, events...)
|
||||
for _, event := range events {
|
||||
addressList := state.GetModuleAddresses(event)
|
||||
addressList := state.Mesh().GetModuleAddresses(event)
|
||||
event = utils.ModuleConnected(event)
|
||||
err := ds.sendAddrList(conn, event, addressList)
|
||||
if err != nil {
|
||||
@@ -50,11 +50,11 @@ func (ds *discoveryService) Subscribe(conn ws.Conn, events []string, state state
|
||||
}
|
||||
}
|
||||
|
||||
func (ds *discoveryService) BroadcastModuleAddresses(moduleName string, state state.ReadState) {
|
||||
func (ds *discoveryService) BroadcastModuleAddresses(moduleName string, state state.ReadonlyState) {
|
||||
ds.lock.RLock()
|
||||
defer ds.lock.RUnlock()
|
||||
event := utils.ModuleConnected(moduleName)
|
||||
addressList := state.GetModuleAddresses(moduleName)
|
||||
addressList := state.Mesh().GetModuleAddresses(moduleName)
|
||||
err := ds.broadcastAddrList(moduleName, event, addressList)
|
||||
if err != nil {
|
||||
log.Errorf(codes.DiscoveryServiceSendModulesError, "broadcast module connected %v", err)
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
log "github.com/integration-system/isp-log"
|
||||
"isp-config-service/cluster"
|
||||
"isp-config-service/codes"
|
||||
"isp-config-service/entity"
|
||||
"isp-config-service/holder"
|
||||
"isp-config-service/model"
|
||||
"isp-config-service/store/state"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
ModuleRegistryService = moduleRegistryService{}
|
||||
)
|
||||
|
||||
type moduleRegistryService struct{}
|
||||
|
||||
func (s moduleRegistryService) HandleModuleConnectedCommand(moduleConnected cluster.ModuleConnected, state state.WritableState) error {
|
||||
module := s.updateModuleLastConnected(moduleConnected.ModuleName, state.WritableModules())
|
||||
if holder.ClusterClient.IsLeader() {
|
||||
_, err := model.ModuleRep.Upsert(module)
|
||||
if err != nil {
|
||||
log.Errorf(codes.DatabaseOperationError, "upsert module: %v", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (moduleRegistryService) updateModuleLastConnected(moduleName string, moduleStore state.WriteableModuleStore) entity.Module {
|
||||
existedModule := moduleStore.GetByName(moduleName)
|
||||
if existedModule == nil {
|
||||
module := moduleStore.Create(moduleName)
|
||||
return module
|
||||
}
|
||||
existedModule.LastConnectedAt = time.Now()
|
||||
moduleStore.Update(*existedModule)
|
||||
return *existedModule
|
||||
}
|
||||
|
||||
func (moduleRegistryService) updateModuleLastDisconnected(moduleName string, moduleStore state.WriteableModuleStore) entity.Module {
|
||||
existedModule := moduleStore.GetByName(moduleName)
|
||||
if existedModule == nil {
|
||||
module := moduleStore.Create(moduleName)
|
||||
return module
|
||||
}
|
||||
existedModule.LastDisconnectedAt = time.Now()
|
||||
moduleStore.Update(*existedModule)
|
||||
return *existedModule
|
||||
}
|
||||
+4
-4
@@ -25,9 +25,9 @@ func (rs *routesService) HandleDisconnect(connId string) {
|
||||
holder.Socket.Rooms().LeaveByConnId(connId, RoutesSubscribersRoom)
|
||||
}
|
||||
|
||||
func (rs *routesService) SubscribeRoutes(conn ws.Conn, state state.ReadState) {
|
||||
func (rs *routesService) SubscribeRoutes(conn ws.Conn, state state.ReadonlyState) {
|
||||
holder.Socket.Rooms().Join(conn, RoutesSubscribersRoom)
|
||||
routes := state.GetRoutes()
|
||||
routes := state.Mesh().GetRoutes()
|
||||
err := rs.sendRoutes(conn, utils.ConfigSendRoutesWhenConnected, routes)
|
||||
if err != nil {
|
||||
log.Errorf(codes.RoutesServiceSendRoutesError, "send routes %v", err)
|
||||
@@ -35,8 +35,8 @@ func (rs *routesService) SubscribeRoutes(conn ws.Conn, state state.ReadState) {
|
||||
|
||||
}
|
||||
|
||||
func (rs *routesService) BroadcastRoutes(state state.ReadState) {
|
||||
routes := state.GetRoutes()
|
||||
func (rs *routesService) BroadcastRoutes(state state.ReadonlyState) {
|
||||
routes := state.Mesh().GetRoutes()
|
||||
err := rs.broadcastRoutes(utils.ConfigSendRoutesChanged, routes)
|
||||
if err != nil {
|
||||
log.Errorf(codes.RoutesServiceSendRoutesError, "broadcast routes %v", err)
|
||||
|
||||
+9
-7
@@ -8,22 +8,24 @@ import (
|
||||
"isp-config-service/store/state"
|
||||
)
|
||||
|
||||
var SchemaService schemaService
|
||||
var (
|
||||
SchemaService schemaService
|
||||
)
|
||||
|
||||
type schemaService struct{}
|
||||
|
||||
func (schemaService) HandleUpdateConfigSchema(schema entity.ConfigSchema, state state.State) (state.State, error) {
|
||||
module := state.GetModuleById(schema.ModuleId)
|
||||
func (schemaService) HandleUpdateConfigSchema(schema entity.ConfigSchema, state state.WritableState) error {
|
||||
module := state.Modules().GetById(schema.ModuleId)
|
||||
if module == nil {
|
||||
return state, errors.Errorf("module with id %s not found", schema.ModuleId)
|
||||
return errors.Errorf("module with id %s not found", schema.ModuleId)
|
||||
}
|
||||
|
||||
if holder.ClusterClient.IsLeader() {
|
||||
schema = state.UpdateSchema(schema)
|
||||
schema = state.WritableSchemas().Upsert(schema)
|
||||
_, err := model.SchemaRep.Upsert(schema)
|
||||
if err != nil {
|
||||
return state, err
|
||||
return err
|
||||
}
|
||||
}
|
||||
return state, nil
|
||||
return nil
|
||||
}
|
||||
+20
-24
@@ -8,58 +8,54 @@ import (
|
||||
"isp-config-service/service"
|
||||
)
|
||||
|
||||
func (s *Store) applyUpdateBackendDeclarationCommand(data []byte) error {
|
||||
func (s *Store) applyUpdateBackendDeclarationCommand(data []byte) (interface{}, error) {
|
||||
declaration := structure.BackendDeclaration{}
|
||||
err := json.Unmarshal(data, &declaration)
|
||||
if err != nil {
|
||||
return errors.Errorf("UpdateBackendDeclarationCommand: %w", err)
|
||||
return nil, errors.WithMessage(err, "unmarshal structure.BackendDeclaration")
|
||||
}
|
||||
state, err := service.ClusterStateService.HandleUpdateBackendDeclarationCommand(declaration, s.state)
|
||||
err = service.ClusterMeshService.HandleUpdateBackendDeclarationCommand(declaration, s.state)
|
||||
if err != nil {
|
||||
return errors.Errorf("UpdateBackendDeclarationCommand: %w", err)
|
||||
return nil, errors.WithMessage(err, "update backend declaration")
|
||||
}
|
||||
s.state = state
|
||||
return nil
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *Store) applyDeleteBackendDeclarationCommand(data []byte) error {
|
||||
func (s *Store) applyDeleteBackendDeclarationCommand(data []byte) (interface{}, error) {
|
||||
declaration := structure.BackendDeclaration{}
|
||||
err := json.Unmarshal(data, &declaration)
|
||||
if err != nil {
|
||||
return errors.Errorf("DeleteBackendDeclarationCommand: %w", err)
|
||||
return nil, errors.WithMessage(err, "unmarshal structure.BackendDeclaration")
|
||||
}
|
||||
state, err := service.ClusterStateService.HandleDeleteBackendDeclarationCommand(declaration, s.state)
|
||||
err = service.ClusterMeshService.HandleDeleteBackendDeclarationCommand(declaration, s.state)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, errors.WithMessage(err, "delete backend declaration")
|
||||
}
|
||||
s.state = state
|
||||
return nil
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *Store) applyUpdateConfigSchema(data []byte) error {
|
||||
func (s *Store) applyUpdateConfigSchema(data []byte) (interface{}, error) {
|
||||
schema := entity.ConfigSchema{}
|
||||
err := json.Unmarshal(data, &schema)
|
||||
if err != nil {
|
||||
return errors.Errorf("UpdateConfigSchemaCommand: %w", err)
|
||||
return nil, errors.WithMessage(err, "unmarshal entity.ConfigSchema")
|
||||
}
|
||||
state, err := service.SchemaService.HandleUpdateConfigSchema(schema, s.state)
|
||||
err = service.SchemaService.HandleUpdateConfigSchema(schema, s.state)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, errors.WithMessage(err, "update config schema")
|
||||
}
|
||||
s.state = state
|
||||
return nil
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *Store) applyModuleConnectedCommand(data []byte) error {
|
||||
func (s *Store) applyModuleConnectedCommand(data []byte) (interface{}, error) {
|
||||
moduleConnected := cluster.ModuleConnected{}
|
||||
err := json.Unmarshal(data, &moduleConnected)
|
||||
if err != nil {
|
||||
return errors.Errorf("ModuleConnectedCommand: %w", err)
|
||||
return nil, errors.WithMessage(err, "unmarshal cluster.ModuleConnected")
|
||||
}
|
||||
state, err := service.ClusterStateService.HandleModuleConnectedCommand(moduleConnected, s.state)
|
||||
err = service.ModuleRegistryService.HandleModuleConnectedCommand(moduleConnected, s.state)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, errors.WithMessage(err, "register module")
|
||||
}
|
||||
s.state = state
|
||||
return nil
|
||||
return nil, nil
|
||||
}
|
||||
+7
-8
@@ -1,30 +1,29 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
log "github.com/integration-system/isp-log"
|
||||
"isp-config-service/codes"
|
||||
"github.com/pkg/errors"
|
||||
"isp-config-service/model"
|
||||
"isp-config-service/store/state"
|
||||
)
|
||||
|
||||
func NewStateFromRepository() state.State {
|
||||
func NewStateFromRepository() (state.State, error) {
|
||||
configs, err := model.ConfigRep.Snapshot()
|
||||
if err != nil {
|
||||
log.Fatalf(codes.RestoreFromRepositoryError, "config repository: %s", err)
|
||||
return state.State{}, errors.WithMessage(err, "restore configs")
|
||||
}
|
||||
schemas, err := model.SchemaRep.Snapshot()
|
||||
if err != nil {
|
||||
log.Fatalf(codes.RestoreFromRepositoryError, "schema repository: %s", err)
|
||||
return state.State{}, errors.WithMessage(err, "load config schemas")
|
||||
}
|
||||
modules, err := model.ModuleRep.Snapshot()
|
||||
if err != nil {
|
||||
log.Fatalf(codes.RestoreFromRepositoryError, "module repository: %s", err)
|
||||
return state.State{}, errors.WithMessage(err, "load modules registry")
|
||||
}
|
||||
commonConfigs, err := model.CommonConfigRep.Snapshot()
|
||||
if err != nil {
|
||||
log.Fatalf(codes.RestoreFromRepositoryError, "module repository: %s", err)
|
||||
return state.State{}, errors.WithMessage(err, "load common configs")
|
||||
}
|
||||
|
||||
st := state.NewStateFromSnapshot(configs, schemas, modules, commonConfigs)
|
||||
return st
|
||||
return st, nil
|
||||
}
|
||||
@@ -2,22 +2,21 @@ package state
|
||||
|
||||
import "isp-config-service/entity"
|
||||
|
||||
type WriteableCommonConfigStore interface {
|
||||
ReadonlyCommonConfigStore
|
||||
Upsert(config entity.CommonConfig)
|
||||
Delete(config entity.CommonConfig)
|
||||
}
|
||||
|
||||
type ReadonlyCommonConfigStore interface {
|
||||
GetByIds(ids []string) []entity.CommonConfig
|
||||
}
|
||||
|
||||
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) GetByIds(ids []string) []entity.CommonConfig {
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
func (cs CommonConfigStore) GetByIds(ids []string) []entity.CommonConfig {
|
||||
idsMap := StringsToMap(ids)
|
||||
configs := make([]entity.CommonConfig, 0, len(ids))
|
||||
for _, config := range cs.configs {
|
||||
@@ -28,6 +27,14 @@ func (cs *CommonConfigStore) GetByIds(ids []string) []entity.CommonConfig {
|
||||
return configs
|
||||
}
|
||||
|
||||
func (cs *CommonConfigStore) Upsert(config entity.CommonConfig) {
|
||||
// TODO
|
||||
}
|
||||
|
||||
func (cs *CommonConfigStore) Delete(config entity.CommonConfig) {
|
||||
// TODO
|
||||
}
|
||||
|
||||
func NewCommonConfigStore() *CommonConfigStore {
|
||||
return &CommonConfigStore{configs: make([]entity.CommonConfig, 0)}
|
||||
}
|
||||
+26
-14
@@ -4,10 +4,36 @@ import (
|
||||
"isp-config-service/entity"
|
||||
)
|
||||
|
||||
type WriteableConfigStore interface {
|
||||
ReadonlyConfigStore
|
||||
Upsert(config entity.Config)
|
||||
Delete(config entity.Config)
|
||||
Activate(config entity.Config)
|
||||
}
|
||||
|
||||
type ReadonlyConfigStore interface {
|
||||
GetActiveByModuleId(moduleId string) *entity.Config
|
||||
GetById(id int64) *entity.Config
|
||||
}
|
||||
|
||||
type ConfigStore struct {
|
||||
configs []entity.Config
|
||||
}
|
||||
|
||||
func (cs ConfigStore) GetActiveByModuleId(moduleId string) *entity.Config {
|
||||
for _, conf := range cs.configs {
|
||||
if conf.ModuleId == moduleId && conf.Active {
|
||||
return &conf
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (cs ConfigStore) GetById(id int64) *entity.Config {
|
||||
// TODO
|
||||
return nil
|
||||
}
|
||||
|
||||
func (cs *ConfigStore) Upsert(config entity.Config) {
|
||||
// TODO
|
||||
}
|
||||
@@ -20,20 +46,6 @@ func (cs *ConfigStore) Activate(config entity.Config) {
|
||||
// TODO
|
||||
}
|
||||
|
||||
func (cs *ConfigStore) GetActiveByModuleId(moduleId string) *entity.Config {
|
||||
for _, conf := range cs.configs {
|
||||
if conf.ModuleId == moduleId && conf.Active {
|
||||
return &conf
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (cs *ConfigStore) GetById(id int64) (*entity.Config, error) {
|
||||
// TODO
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func NewConfigStore() *ConfigStore {
|
||||
return &ConfigStore{configs: make([]entity.Config, 0)}
|
||||
}
|
||||
+59
-46
@@ -4,11 +4,70 @@ import (
|
||||
"github.com/integration-system/isp-lib/structure"
|
||||
)
|
||||
|
||||
type WriteableMesh interface {
|
||||
ReadonlyMesh
|
||||
UpsertBackend(backend structure.BackendDeclaration) (changed bool)
|
||||
DeleteBackend(backend structure.BackendDeclaration) (deleted bool)
|
||||
}
|
||||
|
||||
type ReadonlyMesh interface {
|
||||
CheckBackendChanged(backend structure.BackendDeclaration) (changed bool)
|
||||
BackendExist(backend structure.BackendDeclaration) (exist bool)
|
||||
GetModuleAddresses(moduleName string) []structure.AddressConfiguration
|
||||
GetRoutes() structure.RoutingConfig
|
||||
}
|
||||
|
||||
type Mesh struct {
|
||||
// { "ModuleName": { "address": BackendDeclaration, ...}, ... }
|
||||
modulesMap map[string]NodesMap
|
||||
}
|
||||
|
||||
func (m Mesh) BackendExist(backend structure.BackendDeclaration) (exist bool) {
|
||||
address := backend.Address.GetAddress()
|
||||
if nodes, ok := m.modulesMap[backend.ModuleName]; ok {
|
||||
if _, ok := nodes[address]; ok {
|
||||
exist = true
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (m Mesh) GetModuleAddresses(moduleName string) []structure.AddressConfiguration {
|
||||
addressList := make([]structure.AddressConfiguration, 0)
|
||||
if nodes, ok := m.modulesMap[moduleName]; ok {
|
||||
for _, backend := range nodes {
|
||||
addressList = append(addressList, backend.Address)
|
||||
}
|
||||
}
|
||||
return addressList
|
||||
}
|
||||
|
||||
func (m Mesh) GetRoutes() structure.RoutingConfig {
|
||||
routes := structure.RoutingConfig{}
|
||||
for _, node := range m.modulesMap {
|
||||
for _, backend := range node {
|
||||
routes = append(routes, backend)
|
||||
}
|
||||
}
|
||||
return routes
|
||||
}
|
||||
|
||||
func (m Mesh) CheckBackendChanged(backend structure.BackendDeclaration) (changed bool) {
|
||||
address := backend.Address.GetAddress()
|
||||
if nodes, ok := m.modulesMap[backend.ModuleName]; ok {
|
||||
if oldBackend, ok := nodes[address]; ok {
|
||||
if oldBackend.Version != backend.Version || !oldBackend.IsPathsEqual(backend.Endpoints) || oldBackend.LibVersion != backend.LibVersion {
|
||||
changed = true
|
||||
}
|
||||
} else {
|
||||
changed = true
|
||||
}
|
||||
} else {
|
||||
changed = true
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (m *Mesh) UpsertBackend(backend structure.BackendDeclaration) (changed bool) {
|
||||
address := backend.Address.GetAddress()
|
||||
if nodes, ok := m.modulesMap[backend.ModuleName]; ok {
|
||||
@@ -28,22 +87,6 @@ func (m *Mesh) UpsertBackend(backend structure.BackendDeclaration) (changed bool
|
||||
return
|
||||
}
|
||||
|
||||
func (m *Mesh) CheckBackendChanged(backend structure.BackendDeclaration) (changed bool) {
|
||||
address := backend.Address.GetAddress()
|
||||
if nodes, ok := m.modulesMap[backend.ModuleName]; ok {
|
||||
if oldBackend, ok := nodes[address]; ok {
|
||||
if oldBackend.Version != backend.Version || !oldBackend.IsPathsEqual(backend.Endpoints) || oldBackend.LibVersion != backend.LibVersion {
|
||||
changed = true
|
||||
}
|
||||
} else {
|
||||
changed = true
|
||||
}
|
||||
} else {
|
||||
changed = true
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (m *Mesh) DeleteBackend(backend structure.BackendDeclaration) (deleted bool) {
|
||||
address := backend.Address.GetAddress()
|
||||
if nodes, ok := m.modulesMap[backend.ModuleName]; ok {
|
||||
@@ -58,36 +101,6 @@ func (m *Mesh) DeleteBackend(backend structure.BackendDeclaration) (deleted bool
|
||||
return
|
||||
}
|
||||
|
||||
func (m *Mesh) BackendExist(backend structure.BackendDeclaration) (exist bool) {
|
||||
address := backend.Address.GetAddress()
|
||||
if nodes, ok := m.modulesMap[backend.ModuleName]; ok {
|
||||
if _, ok := nodes[address]; ok {
|
||||
exist = true
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (m *Mesh) GetModuleAddresses(moduleName string) []structure.AddressConfiguration {
|
||||
addressList := make([]structure.AddressConfiguration, 0)
|
||||
if nodes, ok := m.modulesMap[moduleName]; ok {
|
||||
for _, backend := range nodes {
|
||||
addressList = append(addressList, backend.Address)
|
||||
}
|
||||
}
|
||||
return addressList
|
||||
}
|
||||
|
||||
func (m *Mesh) GetRoutes() structure.RoutingConfig {
|
||||
routes := structure.RoutingConfig{}
|
||||
for _, node := range m.modulesMap {
|
||||
for _, backend := range node {
|
||||
routes = append(routes, backend)
|
||||
}
|
||||
}
|
||||
return routes
|
||||
}
|
||||
|
||||
type NodesMap map[string]structure.BackendDeclaration
|
||||
|
||||
func NewMesh() *Mesh {
|
||||
|
||||
+21
-10
@@ -5,19 +5,22 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type WriteableModuleStore interface {
|
||||
ReadonlyModuleStore
|
||||
Update(module entity.Module)
|
||||
Create(name string) entity.Module
|
||||
}
|
||||
|
||||
type ReadonlyModuleStore interface {
|
||||
GetByName(name string) *entity.Module
|
||||
GetById(id string) *entity.Module
|
||||
}
|
||||
|
||||
type ModuleStore struct {
|
||||
modules []entity.Module
|
||||
}
|
||||
|
||||
func (ms *ModuleStore) Update(module entity.Module) {
|
||||
for i := range ms.modules {
|
||||
if ms.modules[i].Id == module.Id {
|
||||
ms.modules[i] = module
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (ms *ModuleStore) GetByName(name string) *entity.Module {
|
||||
func (ms ModuleStore) GetByName(name string) *entity.Module {
|
||||
for _, module := range ms.modules {
|
||||
if module.Name == name {
|
||||
return &module
|
||||
@@ -26,7 +29,7 @@ func (ms *ModuleStore) GetByName(name string) *entity.Module {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ms *ModuleStore) GetById(id string) *entity.Module {
|
||||
func (ms ModuleStore) GetById(id string) *entity.Module {
|
||||
for _, module := range ms.modules {
|
||||
if module.Id == id {
|
||||
return &module
|
||||
@@ -35,6 +38,14 @@ func (ms *ModuleStore) GetById(id string) *entity.Module {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ms *ModuleStore) Update(module entity.Module) {
|
||||
for i := range ms.modules {
|
||||
if ms.modules[i].Id == module.Id {
|
||||
ms.modules[i] = module
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (ms *ModuleStore) Create(name string) entity.Module {
|
||||
module := entity.Module{
|
||||
Id: GenerateId(),
|
||||
|
||||
+20
-10
@@ -4,10 +4,30 @@ import (
|
||||
"isp-config-service/entity"
|
||||
)
|
||||
|
||||
type WriteableSchemaStore interface {
|
||||
ReadonlySchemaStore
|
||||
Upsert(schema entity.ConfigSchema) entity.ConfigSchema
|
||||
}
|
||||
|
||||
type ReadonlySchemaStore interface {
|
||||
GetByModuleId(moduleId int32) *entity.ConfigSchema
|
||||
GetById(id int64) *entity.ConfigSchema
|
||||
}
|
||||
|
||||
type SchemaStore struct {
|
||||
schemas []entity.ConfigSchema
|
||||
}
|
||||
|
||||
func (ss SchemaStore) GetByModuleId(moduleId int32) *entity.ConfigSchema {
|
||||
// TODO
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ss SchemaStore) GetById(id int64) *entity.ConfigSchema {
|
||||
// TODO
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ss *SchemaStore) Upsert(schema entity.ConfigSchema) entity.ConfigSchema {
|
||||
for key, value := range ss.schemas {
|
||||
if value.ModuleId == schema.ModuleId {
|
||||
@@ -21,16 +41,6 @@ func (ss *SchemaStore) Upsert(schema entity.ConfigSchema) entity.ConfigSchema {
|
||||
return schema
|
||||
}
|
||||
|
||||
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)}
|
||||
}
|
||||
+55
-88
@@ -1,10 +1,7 @@
|
||||
package state
|
||||
|
||||
import (
|
||||
"github.com/integration-system/isp-lib/structure"
|
||||
"github.com/pkg/errors"
|
||||
"isp-config-service/entity"
|
||||
"time"
|
||||
)
|
||||
|
||||
type State struct {
|
||||
@@ -15,13 +12,61 @@ type State struct {
|
||||
commonConfigs *CommonConfigStore
|
||||
}
|
||||
|
||||
type ReadState interface {
|
||||
CheckBackendChanged(backend structure.BackendDeclaration) (changed bool)
|
||||
GetModuleAddresses(moduleName string) []structure.AddressConfiguration
|
||||
GetRoutes() structure.RoutingConfig
|
||||
BackendExist(backend structure.BackendDeclaration) (exist bool)
|
||||
GetCompiledConfig(moduleName string) (map[string]interface{}, error)
|
||||
GetModuleByName(string) *entity.Module
|
||||
func (s State) Mesh() ReadonlyMesh {
|
||||
return s.mesh
|
||||
}
|
||||
|
||||
func (s State) Configs() ReadonlyConfigStore {
|
||||
return s.configs
|
||||
}
|
||||
|
||||
func (s State) Schemas() ReadonlySchemaStore {
|
||||
return s.schemas
|
||||
}
|
||||
|
||||
func (s State) Modules() ReadonlyModuleStore {
|
||||
return s.modules
|
||||
}
|
||||
|
||||
func (s State) CommonConfigs() ReadonlyCommonConfigStore {
|
||||
return s.commonConfigs
|
||||
}
|
||||
|
||||
func (s *State) WritableMesh() WriteableMesh {
|
||||
return s.mesh
|
||||
}
|
||||
|
||||
func (s *State) WritableConfigs() WriteableConfigStore {
|
||||
return s.configs
|
||||
}
|
||||
|
||||
func (s *State) WritableSchemas() WriteableSchemaStore {
|
||||
return s.schemas
|
||||
}
|
||||
|
||||
func (s *State) WritableModules() WriteableModuleStore {
|
||||
return s.modules
|
||||
}
|
||||
|
||||
func (s *State) WritableCommonConfigs() WriteableCommonConfigStore {
|
||||
return s.commonConfigs
|
||||
}
|
||||
|
||||
type WritableState interface {
|
||||
ReadonlyState
|
||||
WritableMesh() WriteableMesh
|
||||
WritableConfigs() WriteableConfigStore
|
||||
WritableSchemas() WriteableSchemaStore
|
||||
WritableModules() WriteableModuleStore
|
||||
WritableCommonConfigs() WriteableCommonConfigStore
|
||||
}
|
||||
|
||||
type ReadonlyState interface {
|
||||
Mesh() ReadonlyMesh
|
||||
Configs() ReadonlyConfigStore
|
||||
Schemas() ReadonlySchemaStore
|
||||
Modules() ReadonlyModuleStore
|
||||
CommonConfigs() ReadonlyCommonConfigStore
|
||||
}
|
||||
|
||||
func NewState() State {
|
||||
@@ -43,81 +88,3 @@ func NewStateFromSnapshot(configs []entity.Config, schemas []entity.ConfigSchema
|
||||
commonConfigs: &CommonConfigStore{configs: commConfigs},
|
||||
}
|
||||
}
|
||||
|
||||
func (s State) CheckBackendChanged(backend structure.BackendDeclaration) (changed bool) {
|
||||
return s.mesh.CheckBackendChanged(backend)
|
||||
}
|
||||
|
||||
func (s *State) UpsertBackend(backend structure.BackendDeclaration) (changed bool) {
|
||||
return s.mesh.UpsertBackend(backend)
|
||||
}
|
||||
|
||||
func (s State) GetModuleAddresses(moduleName string) []structure.AddressConfiguration {
|
||||
return s.mesh.GetModuleAddresses(moduleName)
|
||||
}
|
||||
|
||||
func (s State) GetRoutes() structure.RoutingConfig {
|
||||
return s.mesh.GetRoutes()
|
||||
}
|
||||
|
||||
func (s *State) DeleteBackend(backend structure.BackendDeclaration) (deleted bool) {
|
||||
return s.mesh.DeleteBackend(backend)
|
||||
}
|
||||
|
||||
func (s State) BackendExist(backend structure.BackendDeclaration) (exist bool) {
|
||||
return s.mesh.BackendExist(backend)
|
||||
}
|
||||
|
||||
func (s State) GetCompiledConfig(moduleName string) (map[string]interface{}, error) {
|
||||
module := s.modules.GetByName(moduleName)
|
||||
if module == nil {
|
||||
return nil, errors.Errorf("module with name %s not found", moduleName)
|
||||
}
|
||||
config := s.configs.GetActiveByModuleId(module.Id)
|
||||
if config == nil {
|
||||
return nil, errors.Errorf("no active configs for moduleId %s", module.Id)
|
||||
}
|
||||
commonConfigs := s.commonConfigs.GetByIds(config.CommonConfigs)
|
||||
configsToMerge := make([]map[string]interface{}, 0, len(commonConfigs))
|
||||
for _, common := range commonConfigs {
|
||||
configsToMerge = append(configsToMerge, common.Data)
|
||||
}
|
||||
configsToMerge = append(configsToMerge, config.Data)
|
||||
|
||||
resultData := MergeNestedMaps(configsToMerge...)
|
||||
return resultData, nil
|
||||
}
|
||||
|
||||
func (s *State) UpdateModuleLastConnected(moduleName string) entity.Module {
|
||||
existedModule := s.modules.GetByName(moduleName)
|
||||
if existedModule == nil {
|
||||
module := s.modules.Create(moduleName)
|
||||
return module
|
||||
}
|
||||
existedModule.LastConnectedAt = time.Now()
|
||||
s.modules.Update(*existedModule)
|
||||
return *existedModule
|
||||
}
|
||||
|
||||
func (s *State) UpdateModuleLastDisconnected(moduleName string) entity.Module {
|
||||
existedModule := s.modules.GetByName(moduleName)
|
||||
if existedModule == nil {
|
||||
module := s.modules.Create(moduleName)
|
||||
return module
|
||||
}
|
||||
existedModule.LastDisconnectedAt = time.Now()
|
||||
s.modules.Update(*existedModule)
|
||||
return *existedModule
|
||||
}
|
||||
|
||||
func (s State) GetModuleByName(moduleName string) *entity.Module {
|
||||
return s.modules.GetByName(moduleName)
|
||||
}
|
||||
|
||||
func (s State) GetModuleById(moduleId string) *entity.Module {
|
||||
return s.modules.GetById(moduleId)
|
||||
}
|
||||
|
||||
func (s *State) UpdateSchema(schema entity.ConfigSchema) entity.ConfigSchema {
|
||||
return s.schemas.Upsert(schema)
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
package state
|
||||
|
||||
import (
|
||||
"github.com/integration-system/bellows"
|
||||
uuid "github.com/satori/go.uuid"
|
||||
)
|
||||
|
||||
@@ -13,20 +12,6 @@ func StringsToMap(list []string) map[string]struct{} {
|
||||
return newMap
|
||||
}
|
||||
|
||||
func MergeNestedMaps(maps ...map[string]interface{}) map[string]interface{} {
|
||||
if len(maps) == 1 {
|
||||
return maps[0]
|
||||
}
|
||||
result := bellows.Flatten(maps[0])
|
||||
for i := 1; i < len(maps); i++ {
|
||||
newFlatten := bellows.Flatten(maps[i])
|
||||
for k, v := range newFlatten {
|
||||
result[k] = v
|
||||
}
|
||||
}
|
||||
return bellows.Expand(result).(map[string]interface{})
|
||||
}
|
||||
|
||||
func GenerateId() string {
|
||||
uuidV4 := uuid.NewV4()
|
||||
return uuidV4.String()
|
||||
|
||||
+26
-22
@@ -19,31 +19,38 @@ var (
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
state state.State
|
||||
state *state.State
|
||||
lock sync.RWMutex
|
||||
handlers map[uint64]func([]byte) error
|
||||
handlers map[uint64]func([]byte) (interface{}, error)
|
||||
}
|
||||
|
||||
func (s *Store) Apply(l *raft.Log) interface{} {
|
||||
var returnError error
|
||||
s.lock.Lock()
|
||||
defer s.lock.Unlock()
|
||||
|
||||
if len(l.Data) < 8 {
|
||||
log.Fatalf(codes.ApplyLogCommandError, "invalid log data command: %s", l.Data)
|
||||
log.Errorf(codes.ApplyLogCommandError, "invalid log data command: %s", l.Data)
|
||||
}
|
||||
command := binary.BigEndian.Uint64(l.Data[:8])
|
||||
|
||||
var (
|
||||
result interface{}
|
||||
err error
|
||||
)
|
||||
if handler, ok := s.handlers[command]; ok {
|
||||
err := handler(l.Data[8:])
|
||||
if err != nil {
|
||||
returnError = err
|
||||
}
|
||||
result, err = handler(l.Data[8:])
|
||||
} else {
|
||||
log.Fatalf(codes.ApplyLogCommandError, "unknown log command %s", command)
|
||||
log.Errorf(codes.ApplyLogCommandError, "unknown log command %s", command)
|
||||
}
|
||||
|
||||
var logResponse cluster.ApplyLogResponse
|
||||
if returnError != nil {
|
||||
logResponse.ApplyError = returnError.Error()
|
||||
bytes, e := json.Marshal(result)
|
||||
if e != nil {
|
||||
panic(e) // must never occurred
|
||||
}
|
||||
|
||||
logResponse := cluster.ApplyLogResponse{Result: bytes}
|
||||
if err != nil {
|
||||
logResponse.ApplyError = err.Error()
|
||||
}
|
||||
return logResponse
|
||||
}
|
||||
@@ -60,21 +67,18 @@ func (s *Store) Restore(rc io.ReadCloser) error {
|
||||
if err := json.NewDecoder(rc).Decode(&state2); err != nil {
|
||||
return errors.WithMessage(err, "unmarshal store")
|
||||
}
|
||||
s.state = state2
|
||||
s.state = &state2
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) GetReadState() state.ReadState {
|
||||
return s.state
|
||||
}
|
||||
|
||||
func (s *Store) VisitReadState(f func(state.ReadState)) {
|
||||
func (s *Store) VisitReadonlyState(f func(state.ReadonlyState)) {
|
||||
s.lock.RLock()
|
||||
defer s.lock.RUnlock()
|
||||
f(s.GetReadState())
|
||||
|
||||
f(*s.state)
|
||||
}
|
||||
|
||||
func (s *Store) VisitState(f func(state.State)) {
|
||||
func (s *Store) VisitState(f func(writableState state.WritableState)) {
|
||||
s.lock.Lock()
|
||||
defer s.lock.Unlock()
|
||||
f(s.state)
|
||||
@@ -106,9 +110,9 @@ func (f *fsmSnapshot) Release() {}
|
||||
|
||||
func NewStateStore(st state.State) *Store {
|
||||
store := &Store{
|
||||
state: st,
|
||||
state: &st,
|
||||
}
|
||||
store.handlers = map[uint64]func([]byte) error{
|
||||
store.handlers = map[uint64]func([]byte) (interface{}, error){
|
||||
cluster.UpdateBackendDeclarationCommand: store.applyUpdateBackendDeclarationCommand,
|
||||
cluster.DeleteBackendDeclarationCommand: store.applyDeleteBackendDeclarationCommand,
|
||||
cluster.ModuleConnectedCommand: store.applyModuleConnectedCommand,
|
||||
|
||||
+6
-6
@@ -28,8 +28,8 @@ func (h *socketEventHandler) handleModuleReady(conn ws.Conn, data []byte) string
|
||||
}
|
||||
conn.SetBackendDeclaration(declaration)
|
||||
var changed bool
|
||||
h.store.VisitReadState(func(state state.ReadState) {
|
||||
changed = state.CheckBackendChanged(declaration)
|
||||
h.store.VisitReadonlyState(func(state state.ReadonlyState) {
|
||||
changed = state.Mesh().CheckBackendChanged(declaration)
|
||||
})
|
||||
if changed {
|
||||
command := cluster.PrepareUpdateBackendDeclarationCommand(declaration)
|
||||
@@ -39,7 +39,7 @@ func (h *socketEventHandler) handleModuleReady(conn ws.Conn, data []byte) string
|
||||
}
|
||||
if applyLogResponse.ApplyError != "" {
|
||||
log.WithMetadata(map[string]interface{}{
|
||||
"comment": applyLogResponse.Comment,
|
||||
"comment": applyLogResponse.Result,
|
||||
"applyError": applyLogResponse.ApplyError,
|
||||
"commandName": "UpdateBackendDeclarationCommand",
|
||||
}).Warn(codes.SyncApplyError, "apply command")
|
||||
@@ -62,7 +62,7 @@ func (h *socketEventHandler) handleModuleRequirements(conn ws.Conn, data []byte)
|
||||
return err.Error()
|
||||
}
|
||||
|
||||
h.store.VisitReadState(func(state state.ReadState) {
|
||||
h.store.VisitReadonlyState(func(state state.ReadonlyState) {
|
||||
if declaration.RequireRoutes {
|
||||
service.RoutesService.SubscribeRoutes(conn, state)
|
||||
}
|
||||
@@ -83,8 +83,8 @@ func (h *socketEventHandler) handleConfigSchema(conn ws.Conn, data []byte) strin
|
||||
return err.Error()
|
||||
}
|
||||
module := new(entity.Module)
|
||||
h.store.VisitReadState(func(readState state.ReadState) {
|
||||
module = readState.GetModuleByName(moduleName)
|
||||
h.store.VisitReadonlyState(func(readState state.ReadonlyState) {
|
||||
module = readState.Modules().GetByName(moduleName)
|
||||
})
|
||||
if module == nil {
|
||||
return fmt.Sprintf("module with name %s not found", moduleName)
|
||||
|
||||
+1
-1
@@ -22,7 +22,7 @@ func (h *socketEventHandler) SyncApplyCommand(command []byte, commandName string
|
||||
}
|
||||
if applyLogResponse != nil && applyLogResponse.ApplyError != "" {
|
||||
log.WithMetadata(map[string]interface{}{
|
||||
"comment": applyLogResponse.Comment,
|
||||
"result": applyLogResponse.Result,
|
||||
"applyError": applyLogResponse.ApplyError,
|
||||
"commandName": commandName,
|
||||
}).Warnf(codes.SyncApplyError, "apply command")
|
||||
|
||||
+4
-4
@@ -24,7 +24,7 @@ var (
|
||||
|
||||
type socketEventHandler struct {
|
||||
socket *ws.WebsocketServer
|
||||
cluster *cluster.ClusterClient
|
||||
cluster *cluster.Client
|
||||
store *store.Store
|
||||
}
|
||||
|
||||
@@ -52,8 +52,8 @@ func (h *socketEventHandler) handleConnect(conn ws.Conn) {
|
||||
h.SyncApplyCommand(command, "ModuleConnectedCommand")
|
||||
|
||||
var config map[string]interface{}
|
||||
h.store.VisitReadState(func(state state.ReadState) {
|
||||
config, err = state.GetCompiledConfig(moduleName)
|
||||
h.store.VisitReadonlyState(func(state state.ReadonlyState) {
|
||||
config, err = service.ConfigService.GetCompiledConfig(moduleName, state)
|
||||
})
|
||||
if err != nil {
|
||||
EmitConn(conn, utils.ConfigError, err.Error())
|
||||
@@ -84,7 +84,7 @@ func (h *socketEventHandler) handleError(conn ws.Conn, err error) {
|
||||
log.Warnf(codes.SocketIoError, "socket.io: %v", err)
|
||||
}
|
||||
|
||||
func NewSocketEventHandler(socket *ws.WebsocketServer, cluster *cluster.ClusterClient, store *store.Store) *socketEventHandler {
|
||||
func NewSocketEventHandler(socket *ws.WebsocketServer, cluster *cluster.Client, store *store.Store) *socketEventHandler {
|
||||
return &socketEventHandler{
|
||||
socket: socket,
|
||||
cluster: cluster,
|
||||
|
||||
Reference in new issue
Block a user