Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
49fde946ac | ||
|
|
c4ded39e7c | ||
|
|
c8518e9f35 | ||
|
|
97d3a38ed8 | ||
|
|
e840b53978 | ||
|
|
c43e52e9ad | ||
|
|
2a2bd99fcf | ||
|
|
c4f9fc4585 | ||
|
|
0222dfd865 | ||
|
|
11f91b67a8 |
No files matched your search
@@ -1,3 +1,14 @@
|
|||||||
|
### v2.1.2
|
||||||
|
* leader ws client ConnectionReadLimit is now configured by WS.WsConnectionReadLimitKB config param and defaults to 4 MB
|
||||||
|
|
||||||
|
### v2.1.1
|
||||||
|
* update to new endpoint descriptor struct with extra fields introduced in isp-lib v2.1.0
|
||||||
|
|
||||||
|
### v2.1.0
|
||||||
|
* fix panic type casting in shapshot
|
||||||
|
* create empty default config now
|
||||||
|
* add method `/module/get_by_name` to fetch module object by name
|
||||||
|
|
||||||
### v2.0.3
|
### v2.0.3
|
||||||
* fix data race when applyCommandOnLeader in websocket handler
|
* fix data race when applyCommandOnLeader in websocket handler
|
||||||
* update dependencies
|
* update dependencies
|
||||||
|
|||||||
Generated
+12
-5
@@ -277,10 +277,9 @@
|
|||||||
version = "v2.0.2"
|
version = "v2.0.2"
|
||||||
|
|
||||||
[[projects]]
|
[[projects]]
|
||||||
digest = "1:d30832edf4ae7a45e863e216c89bb5f1d66c10ff5b3255b9e007598a048594d7"
|
digest = "1:194932f6894a42dd62acd1092c529befbe576abf50fe929a0e30ae3544ceb6ee"
|
||||||
name = "github.com/integration-system/isp-lib"
|
name = "github.com/integration-system/isp-lib"
|
||||||
packages = [
|
packages = [
|
||||||
"atomic",
|
|
||||||
"backend",
|
"backend",
|
||||||
"bootstrap",
|
"bootstrap",
|
||||||
"config",
|
"config",
|
||||||
@@ -293,8 +292,8 @@
|
|||||||
"utils",
|
"utils",
|
||||||
]
|
]
|
||||||
pruneopts = "UT"
|
pruneopts = "UT"
|
||||||
revision = "abfa9a9776d64e6d04d495bfe00db8ca4dcbe7fc"
|
revision = "4ea9449f1b3f2565b9038b0d4cdda3b02089aa8c"
|
||||||
version = "v2.0.1"
|
version = "v2.1.0"
|
||||||
|
|
||||||
[[projects]]
|
[[projects]]
|
||||||
digest = "1:1562269205ab0c6685c8b0b99511e91b9d3627e4cac3f0288378bc8930e658f1"
|
digest = "1:1562269205ab0c6685c8b0b99511e91b9d3627e4cac3f0288378bc8930e658f1"
|
||||||
@@ -328,6 +327,14 @@
|
|||||||
pruneopts = "UT"
|
pruneopts = "UT"
|
||||||
revision = "5475a8b08e62e41fa886641861ac225e7f91e4e5"
|
revision = "5475a8b08e62e41fa886641861ac225e7f91e4e5"
|
||||||
|
|
||||||
|
[[projects]]
|
||||||
|
digest = "1:965f8051786df58d7d62c8ffa2d90cb84000aab1a167e5c4713ff572cd7e164e"
|
||||||
|
name = "github.com/integration-system/net-mux"
|
||||||
|
packages = ["."]
|
||||||
|
pruneopts = "UT"
|
||||||
|
revision = "9dc223fe46d293b528c8e2a04c43d991bc23a2de"
|
||||||
|
version = "v1.0.0"
|
||||||
|
|
||||||
[[projects]]
|
[[projects]]
|
||||||
digest = "1:01ed62f8f4f574d8aff1d88caee113700a2b44c42351943fa73cc1808f736a50"
|
digest = "1:01ed62f8f4f574d8aff1d88caee113700a2b44c42351943fa73cc1808f736a50"
|
||||||
name = "github.com/jinzhu/inflection"
|
name = "github.com/jinzhu/inflection"
|
||||||
@@ -756,7 +763,6 @@
|
|||||||
"github.com/integration-system/isp-lib-test/docker",
|
"github.com/integration-system/isp-lib-test/docker",
|
||||||
"github.com/integration-system/isp-lib-test/utils",
|
"github.com/integration-system/isp-lib-test/utils",
|
||||||
"github.com/integration-system/isp-lib-test/utils/postgres",
|
"github.com/integration-system/isp-lib-test/utils/postgres",
|
||||||
"github.com/integration-system/isp-lib/atomic",
|
|
||||||
"github.com/integration-system/isp-lib/backend",
|
"github.com/integration-system/isp-lib/backend",
|
||||||
"github.com/integration-system/isp-lib/bootstrap",
|
"github.com/integration-system/isp-lib/bootstrap",
|
||||||
"github.com/integration-system/isp-lib/config",
|
"github.com/integration-system/isp-lib/config",
|
||||||
@@ -766,6 +772,7 @@
|
|||||||
"github.com/integration-system/isp-lib/utils",
|
"github.com/integration-system/isp-lib/utils",
|
||||||
"github.com/integration-system/isp-log",
|
"github.com/integration-system/isp-log",
|
||||||
"github.com/integration-system/isp-log/stdcodes",
|
"github.com/integration-system/isp-log/stdcodes",
|
||||||
|
"github.com/integration-system/net-mux",
|
||||||
"github.com/json-iterator/go",
|
"github.com/json-iterator/go",
|
||||||
"github.com/mohae/deepcopy",
|
"github.com/mohae/deepcopy",
|
||||||
"github.com/pkg/errors",
|
"github.com/pkg/errors",
|
||||||
|
|||||||
+2
-2
@@ -54,8 +54,8 @@ func PrepareDeleteModulesCommand(ids []string) []byte {
|
|||||||
return prepareCommand(DeleteModulesCommand, DeleteModules{Ids: ids})
|
return prepareCommand(DeleteModulesCommand, DeleteModules{Ids: ids})
|
||||||
}
|
}
|
||||||
|
|
||||||
func PrepareActivateConfigCommand(configId string, date time.Time) []byte {
|
func PrepareActivateConfigCommand(configID string, date time.Time) []byte {
|
||||||
return prepareCommand(ActivateConfigCommand, ActivateConfig{ConfigId: configId, Date: date})
|
return prepareCommand(ActivateConfigCommand, ActivateConfig{ConfigId: configID, Date: date})
|
||||||
}
|
}
|
||||||
|
|
||||||
func PrepareDeleteConfigsCommand(ids []string) []byte {
|
func PrepareDeleteConfigsCommand(ids []string) []byte {
|
||||||
|
|||||||
@@ -3,6 +3,11 @@ package cluster
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/cenkalti/backoff"
|
"github.com/cenkalti/backoff"
|
||||||
etp "github.com/integration-system/isp-etp-go/client"
|
etp "github.com/integration-system/isp-etp-go/client"
|
||||||
"github.com/integration-system/isp-lib/config"
|
"github.com/integration-system/isp-lib/config"
|
||||||
@@ -11,10 +16,11 @@ import (
|
|||||||
log "github.com/integration-system/isp-log"
|
log "github.com/integration-system/isp-log"
|
||||||
"isp-config-service/codes"
|
"isp-config-service/codes"
|
||||||
"isp-config-service/conf"
|
"isp-config-service/conf"
|
||||||
"net"
|
)
|
||||||
"net/http"
|
|
||||||
"net/url"
|
var (
|
||||||
"time"
|
// Set from config in main
|
||||||
|
WsConnectionReadLimit int64
|
||||||
)
|
)
|
||||||
|
|
||||||
type SocketLeaderClient struct {
|
type SocketLeaderClient struct {
|
||||||
@@ -63,12 +69,13 @@ func (c *SocketLeaderClient) Close() {
|
|||||||
|
|
||||||
func NewSocketLeaderClient(address string, leaderDisconnectionCallback func()) *SocketLeaderClient {
|
func NewSocketLeaderClient(address string, leaderDisconnectionCallback func()) *SocketLeaderClient {
|
||||||
etpConfig := etp.Config{
|
etpConfig := etp.Config{
|
||||||
HttpClient: http.DefaultClient,
|
HttpClient: http.DefaultClient,
|
||||||
|
ConnectionReadLimit: WsConnectionReadLimit,
|
||||||
}
|
}
|
||||||
client := etp.NewClient(etpConfig)
|
client := etp.NewClient(etpConfig)
|
||||||
leaderClient := &SocketLeaderClient{
|
leaderClient := &SocketLeaderClient{
|
||||||
client: client,
|
client: client,
|
||||||
url: getUrl(address),
|
url: getURL(address),
|
||||||
}
|
}
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
leaderClient.globalCtx = ctx
|
leaderClient.globalCtx = ctx
|
||||||
@@ -90,7 +97,7 @@ func NewSocketLeaderClient(address string, leaderDisconnectionCallback func()) *
|
|||||||
return leaderClient
|
return leaderClient
|
||||||
}
|
}
|
||||||
|
|
||||||
func getUrl(address string) string {
|
func getURL(address string) string {
|
||||||
addr, err := net.ResolveTCPAddr("tcp", address)
|
addr, err := net.ResolveTCPAddr("tcp", address)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(err) // must never occurred
|
panic(err) // must never occurred
|
||||||
|
|||||||
@@ -15,8 +15,8 @@ type Configuration struct {
|
|||||||
|
|
||||||
type ClusterConfiguration struct {
|
type ClusterConfiguration struct {
|
||||||
InMemory bool `schema:"Хранить логи и снэпшоты только в памяти"`
|
InMemory bool `schema:"Хранить логи и снэпшоты только в памяти"`
|
||||||
DataDir string `valid:"required~Required" schema:"Пусть до директории для логов и снэпшотов рафта"`
|
|
||||||
BootstrapCluster bool `schema:"Поднимать кластер и объявлять лидером"`
|
BootstrapCluster bool `schema:"Поднимать кластер и объявлять лидером"`
|
||||||
|
DataDir string `valid:"required~Required" schema:"Пусть до директории для логов и снэпшотов рафта"`
|
||||||
Peers []string `valid:"required~Required" schema:"Адреса всех нод в кластере,формат address:port"`
|
Peers []string `valid:"required~Required" schema:"Адреса всех нод в кластере,формат address:port"`
|
||||||
OuterAddress string `valid:"required~Required" schema:"Внешний адрес ноды"`
|
OuterAddress string `valid:"required~Required" schema:"Внешний адрес ноды"`
|
||||||
ConnectTimeoutSeconds int `valid:"required~Required" schema:"Таймаут подключения"`
|
ConnectTimeoutSeconds int `valid:"required~Required" schema:"Таймаут подключения"`
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/integration-system/isp-lib-test/ctx"
|
"github.com/integration-system/isp-lib-test/ctx"
|
||||||
"github.com/integration-system/isp-lib-test/docker"
|
"github.com/integration-system/isp-lib-test/docker"
|
||||||
@@ -30,6 +31,7 @@ const (
|
|||||||
|
|
||||||
configsNumber = 3
|
configsNumber = 3
|
||||||
maxAwaitingTime = 25 * time.Second
|
maxAwaitingTime = 25 * time.Second
|
||||||
|
attemptTimeout = 300 * time.Millisecond
|
||||||
|
|
||||||
deleteCommonConfigsCommand = "config/common_config/delete_config"
|
deleteCommonConfigsCommand = "config/common_config/delete_config"
|
||||||
getRoutesCommand = "config/routing/get_routes"
|
getRoutesCommand = "config/routing/get_routes"
|
||||||
@@ -109,6 +111,7 @@ func setup(testCtx *ctx.TestContext, runTest func() int) int {
|
|||||||
cfg.Images.Module, c, nil,
|
cfg.Images.Module, c, nil,
|
||||||
docker.WithName(c.GrpcOuterAddress.IP),
|
docker.WithName(c.GrpcOuterAddress.IP),
|
||||||
docker.WithLogger(NewWriteLogger(strconv.Itoa(i)+"_config:", ioutil.Discard, "DeleteCommonConfigsCommand")),
|
docker.WithLogger(NewWriteLogger(strconv.Itoa(i)+"_config:", ioutil.Discard, "DeleteCommonConfigsCommand")),
|
||||||
|
//docker.WithLogger(NewWriteLogger(strconv.Itoa(i)+"_config:", ioutil.Discard, "Apply 10 command")),
|
||||||
//docker.PullImage(cfg.Registry.Username, cfg.Registry.Password),
|
//docker.PullImage(cfg.Registry.Username, cfg.Registry.Password),
|
||||||
docker.WithEnv(peersAddrsEnv),
|
docker.WithEnv(peersAddrsEnv),
|
||||||
)
|
)
|
||||||
@@ -169,8 +172,8 @@ func TestClusterElection(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func getConfigServiceAddress(num int, port string) structure.AddressConfiguration {
|
func getConfigServiceAddress(num int, port string) structure.AddressConfiguration {
|
||||||
lastIp := pgCfg.Address
|
lastIP := pgCfg.Address
|
||||||
ip := net.ParseIP(lastIp).To4()
|
ip := net.ParseIP(lastIP).To4()
|
||||||
ip[3] = byte(int(ip[3]) + num + 1)
|
ip[3] = byte(int(ip[3]) + num + 1)
|
||||||
return structure.AddressConfiguration{
|
return structure.AddressConfiguration{
|
||||||
//IP: fmt.Sprintf("%s-%d", "isp-config-service", num),
|
//IP: fmt.Sprintf("%s-%d", "isp-config-service", num),
|
||||||
@@ -233,11 +236,11 @@ func testGrpcReady(configAddr structure.AddressConfiguration, a *assert.Assertio
|
|||||||
)
|
)
|
||||||
//log.Println("connect to grpc err:", err)
|
//log.Println("connect to grpc err:", err)
|
||||||
return nil, err
|
return nil, err
|
||||||
}, maxAwaitingTime)
|
}, maxAwaitingTime, attemptTimeout)
|
||||||
if !a.NoError(err) {
|
if !a.NoError(err) {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
log.Println("waiting until grpc ready:", time.Now().Sub(start).Round(time.Second))
|
log.Println("waiting until grpc ready:", time.Since(start).Round(time.Second))
|
||||||
return client
|
return client
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -257,27 +260,39 @@ func testRaftReady(client *backend.InternalGrpcClient, a *assert.Assertions) boo
|
|||||||
//log.Println("send grpc request. response: ", response, "err: ", err)
|
//log.Println("send grpc request. response: ", response, "err: ", err)
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
_, _ = await(f, maxAwaitingTime)
|
_, _ = await(f, maxAwaitingTime, attemptTimeout)
|
||||||
log.Println("waiting until raft ready:", time.Now().Sub(start).Round(time.Second))
|
log.Println("waiting until raft ready:", time.Since(start).Round(time.Second))
|
||||||
return a.NoError(err)
|
return a.NoError(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
func getRoutes(client *backend.InternalGrpcClient, a *assert.Assertions) []structure.BackendDeclaration {
|
func getRoutes(client *backend.InternalGrpcClient, a *assert.Assertions) []structure.BackendDeclaration {
|
||||||
var response []structure.BackendDeclaration
|
var response []structure.BackendDeclaration
|
||||||
err := client.Invoke(
|
var err error
|
||||||
getRoutesCommand,
|
f := func() (interface{}, error) {
|
||||||
-1,
|
err = client.Invoke(
|
||||||
nil,
|
getRoutesCommand,
|
||||||
&response,
|
-1,
|
||||||
)
|
nil,
|
||||||
//log.Println("routes:", response)
|
&response,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
} else if len(response) == 0 {
|
||||||
|
return nil, errors.New("zero routes")
|
||||||
|
}
|
||||||
|
|
||||||
|
//log.Println("routes:", response)
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
_, _ = await(f, time.Second, 50*time.Millisecond)
|
||||||
a.NoError(err)
|
a.NoError(err)
|
||||||
return response
|
return response
|
||||||
}
|
}
|
||||||
|
|
||||||
func await(dialer func() (interface{}, error), timeout time.Duration) (interface{}, error) {
|
func await(dialer func() (interface{}, error), timeout, attemptTimeout time.Duration) (interface{}, error) {
|
||||||
retryer := utils.NewRetryer(dialer, timeout)
|
retryer := utils.NewRetryer(dialer, timeout)
|
||||||
retryer.AttemptTimeout = 300 * time.Millisecond
|
retryer.AttemptTimeout = attemptTimeout
|
||||||
return retryer.Do()
|
return retryer.Do()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+12
-6
@@ -29,17 +29,23 @@ type config struct {
|
|||||||
// @Failure 500 {object} structure.GrpcError
|
// @Failure 500 {object} structure.GrpcError
|
||||||
// @Router /config/get_active_config_by_module_name [POST]
|
// @Router /config/get_active_config_by_module_name [POST]
|
||||||
func (c *config) GetActiveConfigByModuleName(request domain.GetByModuleNameRequest) (*entity.Config, error) {
|
func (c *config) GetActiveConfigByModuleName(request domain.GetByModuleNameRequest) (*entity.Config, error) {
|
||||||
var response *entity.Config
|
var (
|
||||||
|
module *entity.Module
|
||||||
|
config *entity.Config
|
||||||
|
)
|
||||||
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
|
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
|
||||||
module := state.Modules().GetByName(request.ModuleName)
|
module = state.Modules().GetByName(request.ModuleName)
|
||||||
if module != nil {
|
if module != nil {
|
||||||
response = state.Configs().GetActiveByModuleId(module.Id)
|
config = state.Configs().GetActiveByModuleId(module.Id)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
if response == nil {
|
if module == nil {
|
||||||
return nil, status.Error(codes.NotFound, utils.ValidationError)
|
return nil, status.Errorf(codes.NotFound, "module with name '%s' not found", request.ModuleName)
|
||||||
}
|
}
|
||||||
return response, nil
|
if config == nil {
|
||||||
|
return nil, status.Errorf(codes.NotFound, "active config for module '%s' not found", request.ModuleName)
|
||||||
|
}
|
||||||
|
return config, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// CreateUpdateConfig godoc
|
// CreateUpdateConfig godoc
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
package controller
|
package controller
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"google.golang.org/grpc/status"
|
||||||
"isp-config-service/cluster"
|
"isp-config-service/cluster"
|
||||||
"isp-config-service/domain"
|
"isp-config-service/domain"
|
||||||
|
"isp-config-service/entity"
|
||||||
"isp-config-service/service"
|
"isp-config-service/service"
|
||||||
"isp-config-service/store"
|
"isp-config-service/store"
|
||||||
"isp-config-service/store/state"
|
"isp-config-service/store/state"
|
||||||
@@ -61,6 +63,28 @@ func (*module) DeleteModules(identities []string) (*domain.DeleteResponse, error
|
|||||||
return &deleteResponse, err
|
return &deleteResponse, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetModuleByName godoc
|
||||||
|
// @Summary Метод получения модуля по имени
|
||||||
|
// @Description Модуль
|
||||||
|
// @Tags Модули
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Param body body domain.GetByModuleNameRequest true "название модуля"
|
||||||
|
// @Success 200 {object} entity.Module
|
||||||
|
// @Failure 500 {object} structure.GrpcError
|
||||||
|
// @Failure 404 {object} structure.GrpcError "модуль с указанным названием не найден"
|
||||||
|
// @Router /module/get_by_name [POST]
|
||||||
|
func (c *module) GetModuleByName(req domain.GetByModuleNameRequest) (*entity.Module, error) {
|
||||||
|
var module *entity.Module
|
||||||
|
c.rstore.VisitReadonlyState(func(readonlyState state.ReadonlyState) {
|
||||||
|
module = readonlyState.Modules().GetByName(req.ModuleName)
|
||||||
|
})
|
||||||
|
if module == nil {
|
||||||
|
return nil, status.Errorf(codes.NotFound, "module with name '%s' not found", req.ModuleName)
|
||||||
|
}
|
||||||
|
return module, nil
|
||||||
|
}
|
||||||
|
|
||||||
func NewModule(rstore *store.Store) *module {
|
func NewModule(rstore *store.Store) *module {
|
||||||
return &module{
|
return &module{
|
||||||
rstore: rstore,
|
rstore: rstore,
|
||||||
|
|||||||
+65
-17
@@ -63,7 +63,7 @@ definitions:
|
|||||||
type: object
|
type: object
|
||||||
endpoints:
|
endpoints:
|
||||||
items:
|
items:
|
||||||
$ref: '#/definitions/structure.EndpointConfig'
|
$ref: '#/definitions/structure.EndpointDescriptor'
|
||||||
type: array
|
type: array
|
||||||
establishedAt:
|
establishedAt:
|
||||||
type: string
|
type: string
|
||||||
@@ -223,6 +223,21 @@ definitions:
|
|||||||
version:
|
version:
|
||||||
type: string
|
type: string
|
||||||
type: object
|
type: object
|
||||||
|
entity.Module:
|
||||||
|
properties:
|
||||||
|
createdAt:
|
||||||
|
type: string
|
||||||
|
id:
|
||||||
|
type: string
|
||||||
|
lastConnectedAt:
|
||||||
|
type: string
|
||||||
|
lastDisconnectedAt:
|
||||||
|
type: string
|
||||||
|
name:
|
||||||
|
type: string
|
||||||
|
required:
|
||||||
|
- name
|
||||||
|
type: object
|
||||||
jsonschema.Definitions:
|
jsonschema.Definitions:
|
||||||
additionalProperties: {}
|
additionalProperties: {}
|
||||||
type: object
|
type: object
|
||||||
@@ -236,7 +251,7 @@ definitions:
|
|||||||
type: string
|
type: string
|
||||||
additionalItems:
|
additionalItems:
|
||||||
description: section 5.9
|
description: section 5.9
|
||||||
type: integer
|
type: string
|
||||||
additionalProperties:
|
additionalProperties:
|
||||||
description: section 5.18
|
description: section 5.18
|
||||||
type: string
|
type: string
|
||||||
@@ -281,7 +296,7 @@ definitions:
|
|||||||
type: string
|
type: string
|
||||||
items:
|
items:
|
||||||
description: section 5.9
|
description: section 5.9
|
||||||
type: integer
|
type: string
|
||||||
maxItems:
|
maxItems:
|
||||||
description: section 5.10
|
description: section 5.10
|
||||||
type: integer
|
type: integer
|
||||||
@@ -296,7 +311,7 @@ definitions:
|
|||||||
type: integer
|
type: integer
|
||||||
media:
|
media:
|
||||||
description: RFC draft-wright-json-schema-hyperschema-00, section 4
|
description: RFC draft-wright-json-schema-hyperschema-00, section 4
|
||||||
type: integer
|
type: string
|
||||||
minItems:
|
minItems:
|
||||||
description: section 5.11
|
description: section 5.11
|
||||||
type: integer
|
type: integer
|
||||||
@@ -314,7 +329,7 @@ definitions:
|
|||||||
type: integer
|
type: integer
|
||||||
not:
|
not:
|
||||||
description: section 5.25
|
description: section 5.25
|
||||||
type: integer
|
type: string
|
||||||
oneOf:
|
oneOf:
|
||||||
description: section 5.24
|
description: section 5.24
|
||||||
items:
|
items:
|
||||||
@@ -354,7 +369,7 @@ definitions:
|
|||||||
type: string
|
type: string
|
||||||
additionalItems:
|
additionalItems:
|
||||||
description: section 5.9
|
description: section 5.9
|
||||||
type: integer
|
type: string
|
||||||
additionalProperties:
|
additionalProperties:
|
||||||
description: section 5.18
|
description: section 5.18
|
||||||
type: string
|
type: string
|
||||||
@@ -400,7 +415,7 @@ definitions:
|
|||||||
type: string
|
type: string
|
||||||
items:
|
items:
|
||||||
description: section 5.9
|
description: section 5.9
|
||||||
type: integer
|
type: string
|
||||||
maxItems:
|
maxItems:
|
||||||
description: section 5.10
|
description: section 5.10
|
||||||
type: integer
|
type: integer
|
||||||
@@ -415,7 +430,7 @@ definitions:
|
|||||||
type: integer
|
type: integer
|
||||||
media:
|
media:
|
||||||
description: RFC draft-wright-json-schema-hyperschema-00, section 4
|
description: RFC draft-wright-json-schema-hyperschema-00, section 4
|
||||||
type: integer
|
type: string
|
||||||
minItems:
|
minItems:
|
||||||
description: section 5.11
|
description: section 5.11
|
||||||
type: integer
|
type: integer
|
||||||
@@ -433,7 +448,7 @@ definitions:
|
|||||||
type: integer
|
type: integer
|
||||||
not:
|
not:
|
||||||
description: section 5.25
|
description: section 5.25
|
||||||
type: integer
|
type: string
|
||||||
oneOf:
|
oneOf:
|
||||||
description: section 5.24
|
description: section 5.24
|
||||||
items:
|
items:
|
||||||
@@ -473,7 +488,7 @@ definitions:
|
|||||||
type: string
|
type: string
|
||||||
additionalItems:
|
additionalItems:
|
||||||
description: section 5.9
|
description: section 5.9
|
||||||
type: integer
|
type: string
|
||||||
additionalProperties:
|
additionalProperties:
|
||||||
description: section 5.18
|
description: section 5.18
|
||||||
type: string
|
type: string
|
||||||
@@ -518,7 +533,7 @@ definitions:
|
|||||||
type: string
|
type: string
|
||||||
items:
|
items:
|
||||||
description: section 5.9
|
description: section 5.9
|
||||||
type: integer
|
type: string
|
||||||
maxItems:
|
maxItems:
|
||||||
description: section 5.10
|
description: section 5.10
|
||||||
type: integer
|
type: integer
|
||||||
@@ -533,7 +548,7 @@ definitions:
|
|||||||
type: integer
|
type: integer
|
||||||
media:
|
media:
|
||||||
description: RFC draft-wright-json-schema-hyperschema-00, section 4
|
description: RFC draft-wright-json-schema-hyperschema-00, section 4
|
||||||
type: integer
|
type: string
|
||||||
minItems:
|
minItems:
|
||||||
description: section 5.11
|
description: section 5.11
|
||||||
type: integer
|
type: integer
|
||||||
@@ -551,7 +566,7 @@ definitions:
|
|||||||
type: integer
|
type: integer
|
||||||
not:
|
not:
|
||||||
description: section 5.25
|
description: section 5.25
|
||||||
type: integer
|
type: string
|
||||||
oneOf:
|
oneOf:
|
||||||
description: section 5.24
|
description: section 5.24
|
||||||
items:
|
items:
|
||||||
@@ -595,7 +610,7 @@ definitions:
|
|||||||
type: object
|
type: object
|
||||||
endpoints:
|
endpoints:
|
||||||
items:
|
items:
|
||||||
$ref: '#/definitions/structure.EndpointConfig'
|
$ref: '#/definitions/structure.EndpointDescriptor'
|
||||||
type: array
|
type: array
|
||||||
libVersion:
|
libVersion:
|
||||||
type: string
|
type: string
|
||||||
@@ -604,14 +619,16 @@ definitions:
|
|||||||
version:
|
version:
|
||||||
type: string
|
type: string
|
||||||
type: object
|
type: object
|
||||||
structure.EndpointConfig:
|
structure.EndpointDescriptor:
|
||||||
properties:
|
properties:
|
||||||
ignoreOnRouter:
|
extra:
|
||||||
type: boolean
|
type: object
|
||||||
inner:
|
inner:
|
||||||
type: boolean
|
type: boolean
|
||||||
path:
|
path:
|
||||||
type: string
|
type: string
|
||||||
|
userAuthRequired:
|
||||||
|
type: boolean
|
||||||
required:
|
required:
|
||||||
- path
|
- path
|
||||||
type: object
|
type: object
|
||||||
@@ -915,6 +932,37 @@ paths:
|
|||||||
summary: Метод удаления объектов модулей по идентификаторам
|
summary: Метод удаления объектов модулей по идентификаторам
|
||||||
tags:
|
tags:
|
||||||
- Модули
|
- Модули
|
||||||
|
/module/get_by_name:
|
||||||
|
post:
|
||||||
|
consumes:
|
||||||
|
- application/json
|
||||||
|
description: Модуль
|
||||||
|
parameters:
|
||||||
|
- description: название модуля
|
||||||
|
in: body
|
||||||
|
name: body
|
||||||
|
required: true
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/domain.GetByModuleNameRequest'
|
||||||
|
type: object
|
||||||
|
produces:
|
||||||
|
- application/json
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: OK
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/entity.Module'
|
||||||
|
"404":
|
||||||
|
description: модуль с указанным названием не найден
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/structure.GrpcError'
|
||||||
|
"500":
|
||||||
|
description: Internal Server Error
|
||||||
|
schema:
|
||||||
|
$ref: '#/definitions/structure.GrpcError'
|
||||||
|
summary: Метод получения модуля по имени
|
||||||
|
tags:
|
||||||
|
- Модули
|
||||||
/module/get_modules_info:
|
/module/get_modules_info:
|
||||||
post:
|
post:
|
||||||
consumes:
|
consumes:
|
||||||
|
|||||||
+1
-1
@@ -27,7 +27,7 @@ type Connection struct {
|
|||||||
LibVersion string
|
LibVersion string
|
||||||
Version string
|
Version string
|
||||||
Address structure.AddressConfiguration
|
Address structure.AddressConfiguration
|
||||||
Endpoints []structure.EndpointConfig `json:",omitempty"`
|
Endpoints []structure.EndpointDescriptor `json:",omitempty"`
|
||||||
EstablishedAt time.Time
|
EstablishedAt time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+6
-5
@@ -9,9 +9,9 @@ import (
|
|||||||
|
|
||||||
type Handlers struct {
|
type Handlers struct {
|
||||||
// ===== MODULE =====
|
// ===== MODULE =====
|
||||||
DeleteModules func(identities []string) (*domain.DeleteResponse, error) `method:"delete_module" group:"module" inner:"true"`
|
DeleteModules func(identities []string) (*domain.DeleteResponse, error) `method:"delete_module" group:"module" inner:"true"`
|
||||||
GetModulesInfo func() ([]domain.ModuleInfo, error) `method:"get_modules_info" group:"module" inner:"true"`
|
GetModulesInfo func() ([]domain.ModuleInfo, error) `method:"get_modules_info" group:"module" inner:"true"`
|
||||||
|
GetModuleByName func(req domain.GetByModuleNameRequest) (*entity.Module, error) `method:"get_by_name" group:"module" inner:"true"`
|
||||||
// ===== CONFIG =====
|
// ===== CONFIG =====
|
||||||
GetActiveConfigByModuleName func(request domain.GetByModuleNameRequest) (*entity.Config, error) `method:"get_active_config_by_module_name" group:"config" inner:"true"`
|
GetActiveConfigByModuleName func(request domain.GetByModuleNameRequest) (*entity.Config, error) `method:"get_active_config_by_module_name" group:"config" inner:"true"`
|
||||||
CreateUpdateConfig func(config domain.CreateUpdateConfigRequest) (*domain.ConfigModuleInfo, error) `method:"create_update_config" group:"config" inner:"true"`
|
CreateUpdateConfig func(config domain.CreateUpdateConfigRequest) (*domain.ConfigModuleInfo, error) `method:"create_update_config" group:"config" inner:"true"`
|
||||||
@@ -34,8 +34,9 @@ type Handlers struct {
|
|||||||
|
|
||||||
func GetHandlers() *Handlers {
|
func GetHandlers() *Handlers {
|
||||||
return &Handlers{
|
return &Handlers{
|
||||||
DeleteModules: controller.Module.DeleteModules,
|
DeleteModules: controller.Module.DeleteModules,
|
||||||
GetModulesInfo: controller.Module.GetModulesAggregatedInfo,
|
GetModulesInfo: controller.Module.GetModulesAggregatedInfo,
|
||||||
|
GetModuleByName: controller.Module.GetModuleByName,
|
||||||
|
|
||||||
GetActiveConfigByModuleName: controller.Config.GetActiveConfigByModuleName,
|
GetActiveConfigByModuleName: controller.Config.GetActiveConfigByModuleName,
|
||||||
CreateUpdateConfig: controller.Config.CreateUpdateConfig,
|
CreateUpdateConfig: controller.Config.CreateUpdateConfig,
|
||||||
|
|||||||
+1
-1
@@ -9,5 +9,5 @@ import (
|
|||||||
var (
|
var (
|
||||||
ClusterClient *cluster.Client
|
ClusterClient *cluster.Client
|
||||||
EtpServer etp.Server
|
EtpServer etp.Server
|
||||||
HttpServer *http.Server
|
HTTPServer *http.Server
|
||||||
)
|
)
|
||||||
@@ -3,6 +3,10 @@ package main
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
|
||||||
"github.com/integration-system/isp-etp-go"
|
"github.com/integration-system/isp-etp-go"
|
||||||
"github.com/integration-system/isp-lib/backend"
|
"github.com/integration-system/isp-lib/backend"
|
||||||
"github.com/integration-system/isp-lib/bootstrap"
|
"github.com/integration-system/isp-lib/bootstrap"
|
||||||
@@ -10,6 +14,7 @@ import (
|
|||||||
"github.com/integration-system/isp-lib/structure"
|
"github.com/integration-system/isp-lib/structure"
|
||||||
"github.com/integration-system/isp-lib/utils"
|
"github.com/integration-system/isp-lib/utils"
|
||||||
log "github.com/integration-system/isp-log"
|
log "github.com/integration-system/isp-log"
|
||||||
|
mux "github.com/integration-system/net-mux"
|
||||||
"github.com/thecodeteam/goodbye"
|
"github.com/thecodeteam/goodbye"
|
||||||
"isp-config-service/cluster"
|
"isp-config-service/cluster"
|
||||||
"isp-config-service/codes"
|
"isp-config-service/codes"
|
||||||
@@ -18,15 +23,11 @@ import (
|
|||||||
"isp-config-service/helper"
|
"isp-config-service/helper"
|
||||||
"isp-config-service/holder"
|
"isp-config-service/holder"
|
||||||
"isp-config-service/model"
|
"isp-config-service/model"
|
||||||
"isp-config-service/mux"
|
|
||||||
"isp-config-service/raft"
|
"isp-config-service/raft"
|
||||||
"isp-config-service/service"
|
"isp-config-service/service"
|
||||||
"isp-config-service/store"
|
"isp-config-service/store"
|
||||||
"isp-config-service/store/state"
|
"isp-config-service/store/state"
|
||||||
"isp-config-service/subs"
|
"isp-config-service/subs"
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
"os"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -36,7 +37,6 @@ const (
|
|||||||
|
|
||||||
var (
|
var (
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
date = "undefined"
|
|
||||||
|
|
||||||
shutdownChan = make(chan struct{})
|
shutdownChan = make(chan struct{})
|
||||||
muxer mux.Mux
|
muxer mux.Mux
|
||||||
@@ -57,6 +57,9 @@ func init() {
|
|||||||
|
|
||||||
// @host localhost:9003
|
// @host localhost:9003
|
||||||
// @BasePath /api/config
|
// @BasePath /api/config
|
||||||
|
|
||||||
|
//go:generate swag init --parseVendor
|
||||||
|
//go:generate rm -f docs/docs.go docs/swagger.json
|
||||||
func main() {
|
func main() {
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
cfg := config.Get().(*conf.Configuration)
|
cfg := config.Get().(*conf.Configuration)
|
||||||
@@ -64,7 +67,7 @@ func main() {
|
|||||||
endpoints := backend.GetEndpoints(cfg.ModuleName, handlers)
|
endpoints := backend.GetEndpoints(cfg.ModuleName, handlers)
|
||||||
address := cfg.GrpcOuterAddress
|
address := cfg.GrpcOuterAddress
|
||||||
if address.IP == "" {
|
if address.IP == "" {
|
||||||
ip, err := getOutboundIp()
|
ip, err := getOutboundIP()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
@@ -78,6 +81,12 @@ func main() {
|
|||||||
Address: address,
|
Address: address,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
connectionReadLimit := defaultWsConnectionReadLimit
|
||||||
|
if cfg.WS.WsConnectionReadLimitKB > 0 {
|
||||||
|
connectionReadLimit = cfg.WS.WsConnectionReadLimitKB << 10
|
||||||
|
}
|
||||||
|
cluster.WsConnectionReadLimit = connectionReadLimit
|
||||||
|
|
||||||
model.DbClient.ReceiveConfiguration(cfg.Database)
|
model.DbClient.ReceiveConfiguration(cfg.Database)
|
||||||
|
|
||||||
httpListener, raftListener, err := initMultiplexer(cfg.WS.Rest)
|
httpListener, raftListener, err := initMultiplexer(cfg.WS.Rest)
|
||||||
@@ -86,7 +95,7 @@ func main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
_, raftStore := initRaft(raftListener, cfg.Cluster, declaration)
|
_, raftStore := initRaft(raftListener, cfg.Cluster, declaration)
|
||||||
initWebsocket(ctx, cfg.WS.WsConnectionReadLimitKB, httpListener, raftStore)
|
initWebsocket(ctx, connectionReadLimit, httpListener, raftStore)
|
||||||
initGrpc(cfg.WS.Grpc, raftStore)
|
initGrpc(cfg.WS.Grpc, raftStore)
|
||||||
|
|
||||||
defer goodbye.Exit(ctx, -1)
|
defer goodbye.Exit(ctx, -1)
|
||||||
@@ -118,11 +127,7 @@ func initMultiplexer(addressConfiguration structure.AddressConfiguration) (net.L
|
|||||||
return httpListener, raftListener, nil
|
return httpListener, raftListener, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func initWebsocket(ctx context.Context, wsConnectionReadLimitKB int64, listener net.Listener, raftStore *store.Store) {
|
func initWebsocket(ctx context.Context, connectionReadLimit int64, listener net.Listener, raftStore *store.Store) {
|
||||||
connectionReadLimit := defaultWsConnectionReadLimit
|
|
||||||
if wsConnectionReadLimitKB > 0 {
|
|
||||||
connectionReadLimit = wsConnectionReadLimitKB << 10
|
|
||||||
}
|
|
||||||
etpConfig := etp.ServerConfig{
|
etpConfig := etp.ServerConfig{
|
||||||
InsecureSkipVerify: true,
|
InsecureSkipVerify: true,
|
||||||
ConnectionReadLimit: connectionReadLimit,
|
ConnectionReadLimit: connectionReadLimit,
|
||||||
@@ -139,7 +144,7 @@ func initWebsocket(ctx context.Context, wsConnectionReadLimitKB int64, listener
|
|||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
holder.EtpServer = etpServer
|
holder.EtpServer = etpServer
|
||||||
holder.HttpServer = httpServer
|
holder.HTTPServer = httpServer
|
||||||
}
|
}
|
||||||
|
|
||||||
func initRaft(listener net.Listener, clusterCfg conf.ClusterConfiguration, declaration structure.BackendDeclaration) (*cluster.Client, *store.Store) {
|
func initRaft(listener net.Listener, clusterCfg conf.ClusterConfiguration, declaration structure.BackendDeclaration) (*cluster.Client, *store.Store) {
|
||||||
@@ -159,7 +164,7 @@ func initRaft(listener net.Listener, clusterCfg conf.ClusterConfiguration, decla
|
|||||||
cfg := config.Get().(*conf.Configuration)
|
cfg := config.Get().(*conf.Configuration)
|
||||||
addr, err := net.ResolveTCPAddr("tcp", address)
|
addr, err := net.ResolveTCPAddr("tcp", address)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(err) // must never occured
|
panic(err) // must never occurred
|
||||||
}
|
}
|
||||||
port := cfg.GrpcOuterAddress.Port
|
port := cfg.GrpcOuterAddress.Port
|
||||||
addressConfiguration := structure.AddressConfiguration{Port: port, IP: addr.IP.String()}
|
addressConfiguration := structure.AddressConfiguration{Port: port, IP: addr.IP.String()}
|
||||||
@@ -196,7 +201,7 @@ func onShutdown(ctx context.Context, _ os.Signal) {
|
|||||||
backend.StopGrpcServer()
|
backend.StopGrpcServer()
|
||||||
holder.EtpServer.Close()
|
holder.EtpServer.Close()
|
||||||
|
|
||||||
if err := holder.HttpServer.Shutdown(ctx); err != nil {
|
if err := holder.HTTPServer.Shutdown(ctx); err != nil {
|
||||||
log.Warnf(codes.ShutdownHttpServerError, "http server shutdown err: %v", err)
|
log.Warnf(codes.ShutdownHttpServerError, "http server shutdown err: %v", err)
|
||||||
} else {
|
} else {
|
||||||
log.Info(codes.ShutdownHttpServerInfo, "http server shutdown success")
|
log.Info(codes.ShutdownHttpServerInfo, "http server shutdown success")
|
||||||
@@ -211,7 +216,7 @@ func onShutdown(ctx context.Context, _ os.Signal) {
|
|||||||
_ = muxer.Close()
|
_ = muxer.Close()
|
||||||
}
|
}
|
||||||
|
|
||||||
func getOutboundIp() (string, error) {
|
func getOutboundIP() (string, error) {
|
||||||
conn, err := net.Dial("udp", "9.9.9.9:80")
|
conn, err := net.Dial("udp", "9.9.9.9:80")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
|
|||||||
@@ -1,44 +0,0 @@
|
|||||||
package mux
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Matcher func([]byte) bool
|
|
||||||
|
|
||||||
// Any is a Matcher that matches any connection.
|
|
||||||
func Any() Matcher {
|
|
||||||
return func(_ []byte) bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var httpMethods = map[string]struct{}{
|
|
||||||
"OPTIONS": {},
|
|
||||||
"HEAD": {},
|
|
||||||
"GET": {},
|
|
||||||
"POST": {},
|
|
||||||
"PUT": {},
|
|
||||||
"PATCH": {},
|
|
||||||
"DELETE": {},
|
|
||||||
"TRACE": {},
|
|
||||||
"CONNECT": {},
|
|
||||||
}
|
|
||||||
|
|
||||||
// HTTP1 only matches the methods in the HTTP request.
|
|
||||||
func HTTP1() Matcher {
|
|
||||||
return func(data []byte) bool {
|
|
||||||
// max length of method
|
|
||||||
l := 7
|
|
||||||
if len(data) < l {
|
|
||||||
l = len(data)
|
|
||||||
}
|
|
||||||
methodB := data[:l]
|
|
||||||
words := bytes.Split(methodB, []byte(" "))
|
|
||||||
if len(words) == 0 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
_, ok := httpMethods[string(words[0])]
|
|
||||||
return ok
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-186
@@ -1,186 +0,0 @@
|
|||||||
package mux
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"github.com/integration-system/isp-lib/atomic"
|
|
||||||
"net"
|
|
||||||
"sync"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
ErrListenerClosed = errors.New("mux: listener closed")
|
|
||||||
ErrNotMatched = errors.New("mux: connection not matched by a matcher")
|
|
||||||
)
|
|
||||||
|
|
||||||
type Mux interface {
|
|
||||||
Match(Matcher) net.Listener
|
|
||||||
Serve() error
|
|
||||||
OnError(func(error))
|
|
||||||
Close() error
|
|
||||||
}
|
|
||||||
|
|
||||||
type matchersListener struct {
|
|
||||||
matcher Matcher
|
|
||||||
listener *muxListener
|
|
||||||
}
|
|
||||||
|
|
||||||
type mux struct {
|
|
||||||
listener net.Listener
|
|
||||||
ml []matchersListener
|
|
||||||
connBufLen int
|
|
||||||
doneCh chan struct{}
|
|
||||||
errHandler func(error)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mux) Match(matcher Matcher) net.Listener {
|
|
||||||
ml := newMuxListener(m.listener, m.connBufLen)
|
|
||||||
m.ml = append(m.ml, matchersListener{matcher: matcher, listener: ml})
|
|
||||||
return ml
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mux) Serve() error {
|
|
||||||
var wg sync.WaitGroup
|
|
||||||
|
|
||||||
defer func() {
|
|
||||||
close(m.doneCh)
|
|
||||||
wg.Wait()
|
|
||||||
|
|
||||||
for _, sl := range m.ml {
|
|
||||||
_ = sl.listener.Close()
|
|
||||||
for c := range sl.listener.connCh {
|
|
||||||
_ = c.Close()
|
|
||||||
}
|
|
||||||
close(sl.listener.connCh)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
for {
|
|
||||||
c, err := m.listener.Accept()
|
|
||||||
if err != nil {
|
|
||||||
if ne, ok := err.(net.Error); ok && ne.Temporary() {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
wg.Add(1)
|
|
||||||
go m.serve(c, &wg)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mux) Close() error {
|
|
||||||
return m.listener.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mux) OnError(f func(error)) {
|
|
||||||
m.errHandler = f
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mux) serve(c net.Conn, wg *sync.WaitGroup) {
|
|
||||||
defer wg.Done()
|
|
||||||
|
|
||||||
buf := getBuffer()
|
|
||||||
n, err := c.Read(buf)
|
|
||||||
data := buf[:n]
|
|
||||||
for _, matcher := range m.ml {
|
|
||||||
matched := matcher.matcher(data)
|
|
||||||
if matched {
|
|
||||||
if matcher.listener.closed.Get() {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
muc := newMuxConn(c, data, err)
|
|
||||||
select {
|
|
||||||
case matcher.listener.connCh <- muc:
|
|
||||||
case <-m.doneCh:
|
|
||||||
putBuffer(buf)
|
|
||||||
_ = c.Close()
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
putBuffer(buf)
|
|
||||||
_ = c.Close()
|
|
||||||
if m.errHandler != nil {
|
|
||||||
m.errHandler(ErrNotMatched)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mux) handleErr(err error) bool {
|
|
||||||
if ne, ok := err.(net.Error); ok {
|
|
||||||
return ne.Temporary()
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func New(l net.Listener) Mux {
|
|
||||||
return &mux{
|
|
||||||
listener: l,
|
|
||||||
connBufLen: 1024,
|
|
||||||
doneCh: make(chan struct{}),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type muxListener struct {
|
|
||||||
root net.Listener
|
|
||||||
connCh chan net.Conn
|
|
||||||
closed *atomic.AtomicBool
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *muxListener) Accept() (net.Conn, error) {
|
|
||||||
if l.closed.Get() {
|
|
||||||
return nil, ErrListenerClosed
|
|
||||||
}
|
|
||||||
c, ok := <-l.connCh
|
|
||||||
if !ok || l.closed.Get() {
|
|
||||||
return nil, ErrListenerClosed
|
|
||||||
}
|
|
||||||
return c, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Close stops listening on address.
|
|
||||||
// Already Accepted connections are not closed.
|
|
||||||
func (l *muxListener) Close() error {
|
|
||||||
l.closed.Set(true)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *muxListener) Addr() net.Addr {
|
|
||||||
return l.root.Addr()
|
|
||||||
}
|
|
||||||
|
|
||||||
func newMuxListener(root net.Listener, connBufLen int) *muxListener {
|
|
||||||
return &muxListener{
|
|
||||||
root: root,
|
|
||||||
connCh: make(chan net.Conn, connBufLen),
|
|
||||||
closed: atomic.NewAtomicBool(false),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type muxConn struct {
|
|
||||||
net.Conn
|
|
||||||
buf []byte
|
|
||||||
lastErr error
|
|
||||||
}
|
|
||||||
|
|
||||||
func newMuxConn(c net.Conn, buf []byte, lastErr error) *muxConn {
|
|
||||||
return &muxConn{
|
|
||||||
Conn: c,
|
|
||||||
buf: buf,
|
|
||||||
lastErr: lastErr,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *muxConn) Read(p []byte) (int, error) {
|
|
||||||
if m.buf != nil {
|
|
||||||
n := copy(p, m.buf)
|
|
||||||
if len(m.buf) == n {
|
|
||||||
putBuffer(m.buf)
|
|
||||||
m.buf = nil
|
|
||||||
} else {
|
|
||||||
m.buf = m.buf[n:]
|
|
||||||
}
|
|
||||||
return n, m.lastErr
|
|
||||||
}
|
|
||||||
return m.Conn.Read(p)
|
|
||||||
}
|
|
||||||
-118
@@ -1,118 +0,0 @@
|
|||||||
package mux
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
"io/ioutil"
|
|
||||||
"log"
|
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestHTTP1(t *testing.T) {
|
|
||||||
a := assert.New(t)
|
|
||||||
path := "/test/"
|
|
||||||
method := "GET"
|
|
||||||
mockResData := []byte("948 res")
|
|
||||||
var responseData []byte
|
|
||||||
|
|
||||||
rootListener := newLocalListener()
|
|
||||||
mux := New(rootListener)
|
|
||||||
httpListener := mux.Match(HTTP1())
|
|
||||||
mux.OnError(func(err error) {
|
|
||||||
a.Fail("connection not matched by a http matcher")
|
|
||||||
})
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
err := mux.Serve()
|
|
||||||
log.Println(err)
|
|
||||||
}()
|
|
||||||
|
|
||||||
handler := func(writer http.ResponseWriter, request *http.Request) {
|
|
||||||
var err error
|
|
||||||
a.Equal(method, request.Method)
|
|
||||||
n, err := writer.Write(mockResData)
|
|
||||||
a.NoError(err)
|
|
||||||
a.Len(mockResData, n)
|
|
||||||
}
|
|
||||||
httpMux := http.NewServeMux()
|
|
||||||
httpMux.HandleFunc(path, handler)
|
|
||||||
httpServer := httptest.NewUnstartedServer(httpMux)
|
|
||||||
httpServer.Listener = httpListener
|
|
||||||
httpServer.Start()
|
|
||||||
|
|
||||||
url := httpServer.URL + path
|
|
||||||
httpClient := httpServer.Client()
|
|
||||||
req, _ := http.NewRequest(method, url, nil)
|
|
||||||
res, err := httpClient.Do(req)
|
|
||||||
a.NoError(err)
|
|
||||||
if a.NotNil(res) {
|
|
||||||
a.Equal(200, res.StatusCode)
|
|
||||||
responseData, err = ioutil.ReadAll(res.Body)
|
|
||||||
}
|
|
||||||
|
|
||||||
time.Sleep(10 * time.Millisecond)
|
|
||||||
a.Equal(mockResData, responseData)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestAny(t *testing.T) {
|
|
||||||
a := assert.New(t)
|
|
||||||
mockReqData := []byte("1 somre")
|
|
||||||
requestData := make([]byte, len(mockReqData))
|
|
||||||
|
|
||||||
rootListener := newLocalListener()
|
|
||||||
mux := New(rootListener)
|
|
||||||
httpListener := mux.Match(HTTP1())
|
|
||||||
tcpListener := mux.Match(Any())
|
|
||||||
go func() {
|
|
||||||
err := mux.Serve()
|
|
||||||
log.Println(err)
|
|
||||||
}()
|
|
||||||
|
|
||||||
handler := func(writer http.ResponseWriter, request *http.Request) {
|
|
||||||
a.Fail("matched http handler")
|
|
||||||
}
|
|
||||||
httpMux := http.NewServeMux()
|
|
||||||
httpMux.HandleFunc("/", handler)
|
|
||||||
httpServer := httptest.NewUnstartedServer(httpMux)
|
|
||||||
httpServer.Listener = httpListener
|
|
||||||
httpServer.Start()
|
|
||||||
|
|
||||||
hadTcpConn := false
|
|
||||||
go func() {
|
|
||||||
for {
|
|
||||||
conn, err := tcpListener.Accept()
|
|
||||||
if hadTcpConn {
|
|
||||||
a.Fail("more than one tcp conn")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
hadTcpConn = true
|
|
||||||
a.NoError(err)
|
|
||||||
_, err = conn.Read(requestData)
|
|
||||||
a.NoError(err)
|
|
||||||
a.Equal(mockReqData, requestData)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
tcpAddr := tcpListener.Addr().String()
|
|
||||||
conn, err := net.Dial("tcp", tcpAddr)
|
|
||||||
a.NoError(err)
|
|
||||||
n, err := conn.Write(mockReqData)
|
|
||||||
a.Len(mockReqData, n)
|
|
||||||
a.NoError(err)
|
|
||||||
|
|
||||||
time.Sleep(10 * time.Millisecond)
|
|
||||||
a.Equal(mockReqData, requestData)
|
|
||||||
a.True(hadTcpConn)
|
|
||||||
}
|
|
||||||
|
|
||||||
func newLocalListener() net.Listener {
|
|
||||||
l, err := net.Listen("tcp", "127.0.0.1:0")
|
|
||||||
if err != nil {
|
|
||||||
panic(fmt.Sprintf("failed to listen on a port: %v", err))
|
|
||||||
}
|
|
||||||
return l
|
|
||||||
}
|
|
||||||
-22
@@ -1,22 +0,0 @@
|
|||||||
package mux
|
|
||||||
|
|
||||||
import (
|
|
||||||
"sync"
|
|
||||||
)
|
|
||||||
|
|
||||||
// could be increased if needed for new matchers
|
|
||||||
const bufferSize = 10
|
|
||||||
|
|
||||||
var pool sync.Pool
|
|
||||||
|
|
||||||
func getBuffer() []byte {
|
|
||||||
b, ok := pool.Get().([]byte)
|
|
||||||
if !ok {
|
|
||||||
b = make([]byte, bufferSize)
|
|
||||||
}
|
|
||||||
return b
|
|
||||||
}
|
|
||||||
|
|
||||||
func putBuffer(b []byte) {
|
|
||||||
pool.Put(b[:cap(b)])
|
|
||||||
}
|
|
||||||
+6
-2
@@ -17,8 +17,8 @@ const (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type ChangeLeaderNotification struct {
|
type ChangeLeaderNotification struct {
|
||||||
IsLeader bool
|
|
||||||
CurrentLeaderAddress string
|
CurrentLeaderAddress string
|
||||||
|
IsLeader bool
|
||||||
LeaderElected bool
|
LeaderElected bool
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,11 +55,13 @@ func (r *Raft) LeaderCh() <-chan ChangeLeaderNotification {
|
|||||||
func (r *Raft) GracefulShutdown() error {
|
func (r *Raft) GracefulShutdown() error {
|
||||||
r.r.DeregisterObserver(r.leaderObs)
|
r.r.DeregisterObserver(r.leaderObs)
|
||||||
close(r.closer)
|
close(r.closer)
|
||||||
close(r.changeLeaderCh)
|
close(r.leaderObsCh)
|
||||||
return r.r.Shutdown().Error()
|
return r.r.Shutdown().Error()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Raft) listenLeader() {
|
func (r *Raft) listenLeader() {
|
||||||
|
defer close(r.changeLeaderCh)
|
||||||
|
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case _, ok := <-r.leaderObsCh:
|
case _, ok := <-r.leaderObsCh:
|
||||||
@@ -73,6 +75,8 @@ func (r *Raft) listenLeader() {
|
|||||||
CurrentLeaderAddress: string(currentLeader),
|
CurrentLeaderAddress: string(currentLeader),
|
||||||
LeaderElected: currentLeader != "",
|
LeaderElected: currentLeader != "",
|
||||||
}:
|
}:
|
||||||
|
case <-r.closer:
|
||||||
|
return
|
||||||
default:
|
default:
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -73,8 +73,8 @@ func (s commonConfigService) HandleUpsertConfigCommand(upsertConfig cluster.Upse
|
|||||||
return cluster.NewResponse(config)
|
return cluster.NewResponse(config)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s commonConfigService) GetCommonConfigLinks(commonConfigId string, state state.ReadonlyState) domain.CommonConfigLinks {
|
func (s commonConfigService) GetCommonConfigLinks(commonConfigID string, state state.ReadonlyState) domain.CommonConfigLinks {
|
||||||
configs := state.Configs().FilterByCommonConfigs([]string{commonConfigId})
|
configs := state.Configs().FilterByCommonConfigs([]string{commonConfigID})
|
||||||
result := make(domain.CommonConfigLinks)
|
result := make(domain.CommonConfigLinks)
|
||||||
for _, c := range configs {
|
for _, c := range configs {
|
||||||
module := state.Modules().GetById(c.ModuleId)
|
module := state.Modules().GetById(c.ModuleId)
|
||||||
|
|||||||
+2
-2
@@ -158,8 +158,8 @@ func (cs configService) HandleUpsertConfigCommand(upsertConfig cluster.UpsertCon
|
|||||||
|
|
||||||
func (cs configService) BroadcastNewConfig(state state.ReadonlyState, configs ...entity.Config) {
|
func (cs configService) BroadcastNewConfig(state state.ReadonlyState, configs ...entity.Config) {
|
||||||
for _, cfg := range configs {
|
for _, cfg := range configs {
|
||||||
moduleId := cfg.ModuleId
|
moduleID := cfg.ModuleId
|
||||||
module := state.Modules().GetById(moduleId)
|
module := state.Modules().GetById(moduleID)
|
||||||
moduleName := module.Name
|
moduleName := module.Name
|
||||||
room := moduleName + ConfigWatchersRoomSuffix
|
room := moduleName + ConfigWatchersRoomSuffix
|
||||||
|
|
||||||
|
|||||||
+19
-19
@@ -24,12 +24,12 @@ type discoveryService struct {
|
|||||||
lock sync.RWMutex
|
lock sync.RWMutex
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ds *discoveryService) HandleDisconnect(connId string) {
|
func (ds *discoveryService) HandleDisconnect(connID string) {
|
||||||
ds.lock.Lock()
|
ds.lock.Lock()
|
||||||
defer ds.lock.Unlock()
|
defer ds.lock.Unlock()
|
||||||
if events, ok := ds.subs[connId]; ok {
|
if events, ok := ds.subs[connID]; ok {
|
||||||
holder.EtpServer.Rooms().LeaveByConnId(connId, events...)
|
holder.EtpServer.Rooms().LeaveByConnId(connID, events...)
|
||||||
delete(ds.subs, connId)
|
delete(ds.subs, connID)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,28 +76,28 @@ func (ds *discoveryService) BroadcastModuleAddresses(moduleName string, mesh sta
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (ds *discoveryService) broadcastAddrList(room string, event string, addressList []structure.AddressConfiguration) error {
|
func (ds *discoveryService) broadcastAddrList(room string, event string, addressList []structure.AddressConfiguration) error {
|
||||||
if bytes, err := json.Marshal(addressList); err != nil {
|
bytes, err := json.Marshal(addressList)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
err = holder.EtpServer.BroadcastToRoom(room, event, bytes)
|
||||||
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
} else {
|
|
||||||
err = holder.EtpServer.BroadcastToRoom(room, event, bytes)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ds *discoveryService) sendAddrList(conn etp.Conn, event string, addressList []structure.AddressConfiguration) error {
|
func (ds *discoveryService) sendAddrList(conn etp.Conn, event string, addressList []structure.AddressConfiguration) error {
|
||||||
if bytes, err := json.Marshal(addressList); err != nil {
|
bytes, err := json.Marshal(addressList)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
bf := backoff.WithMaxRetries(backoff.NewConstantBackOff(100*time.Millisecond), 3)
|
||||||
|
err = backoff.Retry(func() error {
|
||||||
|
return conn.Emit(context.Background(), event, bytes)
|
||||||
|
}, bf)
|
||||||
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
} else {
|
|
||||||
bf := backoff.WithMaxRetries(backoff.NewConstantBackOff(100*time.Millisecond), 3)
|
|
||||||
err := backoff.Retry(func() error {
|
|
||||||
return conn.Emit(context.Background(), event, bytes)
|
|
||||||
}, bf)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
+8
-8
@@ -22,8 +22,8 @@ var RoutesService routesService
|
|||||||
|
|
||||||
type routesService struct{}
|
type routesService struct{}
|
||||||
|
|
||||||
func (rs *routesService) HandleDisconnect(connId string) {
|
func (rs *routesService) HandleDisconnect(connID string) {
|
||||||
holder.EtpServer.Rooms().LeaveByConnId(connId, RoutesSubscribersRoom)
|
holder.EtpServer.Rooms().LeaveByConnId(connID, RoutesSubscribersRoom)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (rs *routesService) SubscribeRoutes(conn etp.Conn, mesh state.ReadonlyMesh) {
|
func (rs *routesService) SubscribeRoutes(conn etp.Conn, mesh state.ReadonlyMesh) {
|
||||||
@@ -48,13 +48,13 @@ func (rs *routesService) BroadcastRoutes(mesh state.ReadonlyMesh) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (rs *routesService) broadcastRoutes(event string, routes structure.RoutingConfig) error {
|
func (rs *routesService) broadcastRoutes(event string, routes structure.RoutingConfig) error {
|
||||||
if bytes, err := json.Marshal(routes); err != nil {
|
bytes, err := json.Marshal(routes)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
err = holder.EtpServer.BroadcastToRoom(RoutesSubscribersRoom, event, bytes)
|
||||||
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
} else {
|
|
||||||
err = holder.EtpServer.BroadcastToRoom(RoutesSubscribersRoom, event, bytes)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
+5
-5
@@ -6,22 +6,22 @@ import (
|
|||||||
"isp-config-service/store/state"
|
"isp-config-service/store/state"
|
||||||
)
|
)
|
||||||
|
|
||||||
func NewStateFromRepository() (state.State, error) {
|
func NewStateFromRepository() (*state.State, error) {
|
||||||
configs, err := model.ConfigRep.Snapshot()
|
configs, err := model.ConfigRep.Snapshot()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return state.State{}, errors.WithMessage(err, "restore configs")
|
return nil, errors.WithMessage(err, "restore configs")
|
||||||
}
|
}
|
||||||
schemas, err := model.SchemaRep.Snapshot()
|
schemas, err := model.SchemaRep.Snapshot()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return state.State{}, errors.WithMessage(err, "load config schemas")
|
return nil, errors.WithMessage(err, "load config schemas")
|
||||||
}
|
}
|
||||||
modules, err := model.ModuleRep.Snapshot()
|
modules, err := model.ModuleRep.Snapshot()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return state.State{}, errors.WithMessage(err, "load modules registry")
|
return nil, errors.WithMessage(err, "load modules registry")
|
||||||
}
|
}
|
||||||
commonConfigs, err := model.CommonConfigRep.Snapshot()
|
commonConfigs, err := model.CommonConfigRep.Snapshot()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return state.State{}, errors.WithMessage(err, "load common configs")
|
return nil, errors.WithMessage(err, "load common configs")
|
||||||
}
|
}
|
||||||
|
|
||||||
st := state.NewStateFromSnapshot(configs, schemas, modules, commonConfigs)
|
st := state.NewStateFromSnapshot(configs, schemas, modules, commonConfigs)
|
||||||
|
|||||||
@@ -18,13 +18,13 @@ type ReadonlyCommonConfigStore interface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type CommonConfigStore struct {
|
type CommonConfigStore struct {
|
||||||
configs []entity.CommonConfig
|
Configs []entity.CommonConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cs CommonConfigStore) GetByIds(ids []string) []entity.CommonConfig {
|
func (cs CommonConfigStore) GetByIds(ids []string) []entity.CommonConfig {
|
||||||
idsMap := StringsToMap(ids)
|
idsMap := StringsToMap(ids)
|
||||||
configs := make([]entity.CommonConfig, 0, len(ids))
|
configs := make([]entity.CommonConfig, 0, len(ids))
|
||||||
for _, config := range cs.configs {
|
for _, config := range cs.Configs {
|
||||||
if _, found := idsMap[config.Id]; found {
|
if _, found := idsMap[config.Id]; found {
|
||||||
configs = append(configs, config)
|
configs = append(configs, config)
|
||||||
}
|
}
|
||||||
@@ -34,7 +34,7 @@ func (cs CommonConfigStore) GetByIds(ids []string) []entity.CommonConfig {
|
|||||||
|
|
||||||
func (cs CommonConfigStore) GetByName(name string) []entity.CommonConfig {
|
func (cs CommonConfigStore) GetByName(name string) []entity.CommonConfig {
|
||||||
configs := make([]entity.CommonConfig, 0)
|
configs := make([]entity.CommonConfig, 0)
|
||||||
for _, config := range cs.configs {
|
for _, config := range cs.Configs {
|
||||||
if config.Name == name {
|
if config.Name == name {
|
||||||
configs = append(configs, config)
|
configs = append(configs, config)
|
||||||
}
|
}
|
||||||
@@ -49,14 +49,14 @@ func (cs *CommonConfigStore) Create(config entity.CommonConfig) entity.CommonCon
|
|||||||
if config.Data == nil {
|
if config.Data == nil {
|
||||||
config.Data = make(entity.ConfigData)
|
config.Data = make(entity.ConfigData)
|
||||||
}
|
}
|
||||||
cs.configs = append(cs.configs, config)
|
cs.Configs = append(cs.Configs, config)
|
||||||
return config
|
return config
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cs *CommonConfigStore) UpdateById(config entity.CommonConfig) {
|
func (cs *CommonConfigStore) UpdateById(config entity.CommonConfig) {
|
||||||
for i := range cs.configs {
|
for i := range cs.Configs {
|
||||||
if cs.configs[i].Id == config.Id {
|
if cs.Configs[i].Id == config.Id {
|
||||||
cs.configs[i] = config
|
cs.Configs[i] = config
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -65,12 +65,12 @@ func (cs *CommonConfigStore) UpdateById(config entity.CommonConfig) {
|
|||||||
func (cs *CommonConfigStore) DeleteByIds(ids []string) int {
|
func (cs *CommonConfigStore) DeleteByIds(ids []string) int {
|
||||||
idsMap := StringsToMap(ids)
|
idsMap := StringsToMap(ids)
|
||||||
var deleted int
|
var deleted int
|
||||||
for i := 0; i < len(cs.configs); i++ {
|
for i := 0; i < len(cs.Configs); i++ {
|
||||||
id := cs.configs[i].Id
|
id := cs.Configs[i].Id
|
||||||
if _, ok := idsMap[id]; ok {
|
if _, ok := idsMap[id]; ok {
|
||||||
// change configs ordering
|
// change configs ordering
|
||||||
cs.configs[i] = cs.configs[len(cs.configs)-1]
|
cs.Configs[i] = cs.Configs[len(cs.Configs)-1]
|
||||||
cs.configs = cs.configs[:len(cs.configs)-1]
|
cs.Configs = cs.Configs[:len(cs.Configs)-1]
|
||||||
deleted++
|
deleted++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -78,11 +78,11 @@ func (cs *CommonConfigStore) DeleteByIds(ids []string) int {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (cs *CommonConfigStore) GetAll() []entity.CommonConfig {
|
func (cs *CommonConfigStore) GetAll() []entity.CommonConfig {
|
||||||
response := make([]entity.CommonConfig, len(cs.configs))
|
response := make([]entity.CommonConfig, len(cs.Configs))
|
||||||
copy(response, cs.configs)
|
copy(response, cs.Configs)
|
||||||
return response
|
return response
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewCommonConfigStore() *CommonConfigStore {
|
func NewCommonConfigStore() *CommonConfigStore {
|
||||||
return &CommonConfigStore{configs: make([]entity.CommonConfig, 0)}
|
return &CommonConfigStore{Configs: make([]entity.CommonConfig, 0)}
|
||||||
}
|
}
|
||||||
+23
-23
@@ -25,11 +25,11 @@ type ReadonlyConfigStore interface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type ConfigStore struct {
|
type ConfigStore struct {
|
||||||
configs []entity.Config
|
Configs []entity.Config
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cs ConfigStore) GetActiveByModuleId(moduleId string) *entity.Config {
|
func (cs ConfigStore) GetActiveByModuleId(moduleId string) *entity.Config {
|
||||||
for _, conf := range cs.configs {
|
for _, conf := range cs.Configs {
|
||||||
if conf.ModuleId == moduleId && conf.Active {
|
if conf.ModuleId == moduleId && conf.Active {
|
||||||
return &conf
|
return &conf
|
||||||
}
|
}
|
||||||
@@ -40,7 +40,7 @@ func (cs ConfigStore) GetActiveByModuleId(moduleId string) *entity.Config {
|
|||||||
func (cs ConfigStore) GetByIds(ids []string) []entity.Config {
|
func (cs ConfigStore) GetByIds(ids []string) []entity.Config {
|
||||||
idsMap := StringsToMap(ids)
|
idsMap := StringsToMap(ids)
|
||||||
result := make([]entity.Config, 0, len(ids))
|
result := make([]entity.Config, 0, len(ids))
|
||||||
for _, conf := range cs.configs {
|
for _, conf := range cs.Configs {
|
||||||
if _, ok := idsMap[conf.Id]; ok {
|
if _, ok := idsMap[conf.Id]; ok {
|
||||||
result = append(result, conf)
|
result = append(result, conf)
|
||||||
}
|
}
|
||||||
@@ -51,7 +51,7 @@ func (cs ConfigStore) GetByIds(ids []string) []entity.Config {
|
|||||||
func (cs ConfigStore) GetByModuleIds(ids []string) []entity.Config {
|
func (cs ConfigStore) GetByModuleIds(ids []string) []entity.Config {
|
||||||
idsMap := StringsToMap(ids)
|
idsMap := StringsToMap(ids)
|
||||||
result := make([]entity.Config, 0, len(ids))
|
result := make([]entity.Config, 0, len(ids))
|
||||||
for _, conf := range cs.configs {
|
for _, conf := range cs.Configs {
|
||||||
if _, ok := idsMap[conf.ModuleId]; ok {
|
if _, ok := idsMap[conf.ModuleId]; ok {
|
||||||
result = append(result, conf)
|
result = append(result, conf)
|
||||||
}
|
}
|
||||||
@@ -73,14 +73,14 @@ func (cs *ConfigStore) Create(config entity.Config) entity.Config {
|
|||||||
if config.CommonConfigs == nil {
|
if config.CommonConfigs == nil {
|
||||||
config.CommonConfigs = make([]string, 0)
|
config.CommonConfigs = make([]string, 0)
|
||||||
}
|
}
|
||||||
cs.configs = append(cs.configs, config)
|
cs.Configs = append(cs.Configs, config)
|
||||||
return config
|
return config
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cs *ConfigStore) UpdateById(config entity.Config) {
|
func (cs *ConfigStore) UpdateById(config entity.Config) {
|
||||||
for i := range cs.configs {
|
for i := range cs.Configs {
|
||||||
if cs.configs[i].Id == config.Id {
|
if cs.Configs[i].Id == config.Id {
|
||||||
cs.configs[i] = config
|
cs.Configs[i] = config
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -88,10 +88,10 @@ func (cs *ConfigStore) UpdateById(config entity.Config) {
|
|||||||
|
|
||||||
func (cs *ConfigStore) calcNewVersion(moduleId string) int32 {
|
func (cs *ConfigStore) calcNewVersion(moduleId string) int32 {
|
||||||
var maxVersion int32 = 0
|
var maxVersion int32 = 0
|
||||||
for i := range cs.configs {
|
for i := range cs.Configs {
|
||||||
if cs.configs[i].ModuleId == moduleId {
|
if cs.Configs[i].ModuleId == moduleId {
|
||||||
if cs.configs[i].Version > maxVersion {
|
if cs.Configs[i].Version > maxVersion {
|
||||||
maxVersion = cs.configs[i].Version
|
maxVersion = cs.Configs[i].Version
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -101,12 +101,12 @@ func (cs *ConfigStore) calcNewVersion(moduleId string) int32 {
|
|||||||
func (cs *ConfigStore) DeleteByIds(ids []string) int {
|
func (cs *ConfigStore) DeleteByIds(ids []string) int {
|
||||||
idsMap := StringsToMap(ids)
|
idsMap := StringsToMap(ids)
|
||||||
var deleted int
|
var deleted int
|
||||||
for i := 0; i < len(cs.configs); i++ {
|
for i := 0; i < len(cs.Configs); i++ {
|
||||||
id := cs.configs[i].Id
|
id := cs.Configs[i].Id
|
||||||
if _, ok := idsMap[id]; ok {
|
if _, ok := idsMap[id]; ok {
|
||||||
// change configs ordering
|
// change configs ordering
|
||||||
cs.configs[i] = cs.configs[len(cs.configs)-1]
|
cs.Configs[i] = cs.Configs[len(cs.Configs)-1]
|
||||||
cs.configs = cs.configs[:len(cs.configs)-1]
|
cs.Configs = cs.Configs[:len(cs.Configs)-1]
|
||||||
deleted++
|
deleted++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -124,11 +124,11 @@ func (cs *ConfigStore) Activate(config entity.Config, date time.Time) []entity.C
|
|||||||
|
|
||||||
func (cs *ConfigStore) deactivate(moduleId string, date time.Time) []entity.Config {
|
func (cs *ConfigStore) deactivate(moduleId string, date time.Time) []entity.Config {
|
||||||
affected := make([]entity.Config, 0)
|
affected := make([]entity.Config, 0)
|
||||||
for i := range cs.configs {
|
for i := range cs.Configs {
|
||||||
if cs.configs[i].ModuleId == moduleId && cs.configs[i].Active {
|
if cs.Configs[i].ModuleId == moduleId && cs.Configs[i].Active {
|
||||||
cs.configs[i].Active = false
|
cs.Configs[i].Active = false
|
||||||
cs.configs[i].UpdatedAt = date
|
cs.Configs[i].UpdatedAt = date
|
||||||
affected = append(affected, cs.configs[i])
|
affected = append(affected, cs.Configs[i])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return affected
|
return affected
|
||||||
@@ -137,7 +137,7 @@ func (cs *ConfigStore) deactivate(moduleId string, date time.Time) []entity.Conf
|
|||||||
func (cs *ConfigStore) FilterByCommonConfigs(commonIds []string) []entity.Config {
|
func (cs *ConfigStore) FilterByCommonConfigs(commonIds []string) []entity.Config {
|
||||||
idsMap := StringsToMap(commonIds)
|
idsMap := StringsToMap(commonIds)
|
||||||
result := make([]entity.Config, 0)
|
result := make([]entity.Config, 0)
|
||||||
for _, cfg := range cs.configs {
|
for _, cfg := range cs.Configs {
|
||||||
for _, commonId := range cfg.CommonConfigs {
|
for _, commonId := range cfg.CommonConfigs {
|
||||||
if _, ok := idsMap[commonId]; ok {
|
if _, ok := idsMap[commonId]; ok {
|
||||||
result = append(result, cfg)
|
result = append(result, cfg)
|
||||||
@@ -149,5 +149,5 @@ func (cs *ConfigStore) FilterByCommonConfigs(commonIds []string) []entity.Config
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewConfigStore() *ConfigStore {
|
func NewConfigStore() *ConfigStore {
|
||||||
return &ConfigStore{configs: make([]entity.Config, 0)}
|
return &ConfigStore{Configs: make([]entity.Config, 0)}
|
||||||
}
|
}
|
||||||
+11
-11
@@ -22,12 +22,12 @@ type NodesMap map[string]structure.BackendDeclaration
|
|||||||
|
|
||||||
type Mesh struct {
|
type Mesh struct {
|
||||||
// { "ModuleName": { "address": BackendDeclaration, ...}, ... }
|
// { "ModuleName": { "address": BackendDeclaration, ...}, ... }
|
||||||
modulesMap map[string]NodesMap
|
ModulesMap map[string]NodesMap
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m Mesh) BackendExist(backend structure.BackendDeclaration) (exist bool) {
|
func (m Mesh) BackendExist(backend structure.BackendDeclaration) (exist bool) {
|
||||||
address := backend.Address.GetAddress()
|
address := backend.Address.GetAddress()
|
||||||
if nodes, ok := m.modulesMap[backend.ModuleName]; ok {
|
if nodes, ok := m.ModulesMap[backend.ModuleName]; ok {
|
||||||
if _, ok := nodes[address]; ok {
|
if _, ok := nodes[address]; ok {
|
||||||
exist = true
|
exist = true
|
||||||
}
|
}
|
||||||
@@ -37,7 +37,7 @@ func (m Mesh) BackendExist(backend structure.BackendDeclaration) (exist bool) {
|
|||||||
|
|
||||||
func (m Mesh) GetBackends(module string) []structure.BackendDeclaration {
|
func (m Mesh) GetBackends(module string) []structure.BackendDeclaration {
|
||||||
declarations := make([]structure.BackendDeclaration, 0)
|
declarations := make([]structure.BackendDeclaration, 0)
|
||||||
if nodes, ok := m.modulesMap[module]; ok {
|
if nodes, ok := m.ModulesMap[module]; ok {
|
||||||
for _, backend := range nodes {
|
for _, backend := range nodes {
|
||||||
declarations = append(declarations, backend)
|
declarations = append(declarations, backend)
|
||||||
}
|
}
|
||||||
@@ -47,7 +47,7 @@ func (m Mesh) GetBackends(module string) []structure.BackendDeclaration {
|
|||||||
|
|
||||||
func (m Mesh) GetModuleAddresses(moduleName string) []structure.AddressConfiguration {
|
func (m Mesh) GetModuleAddresses(moduleName string) []structure.AddressConfiguration {
|
||||||
addressList := make([]structure.AddressConfiguration, 0)
|
addressList := make([]structure.AddressConfiguration, 0)
|
||||||
if nodes, ok := m.modulesMap[moduleName]; ok {
|
if nodes, ok := m.ModulesMap[moduleName]; ok {
|
||||||
for _, backend := range nodes {
|
for _, backend := range nodes {
|
||||||
addressList = append(addressList, backend.Address)
|
addressList = append(addressList, backend.Address)
|
||||||
}
|
}
|
||||||
@@ -57,7 +57,7 @@ func (m Mesh) GetModuleAddresses(moduleName string) []structure.AddressConfigura
|
|||||||
|
|
||||||
func (m Mesh) GetRoutes() structure.RoutingConfig {
|
func (m Mesh) GetRoutes() structure.RoutingConfig {
|
||||||
routes := structure.RoutingConfig{}
|
routes := structure.RoutingConfig{}
|
||||||
for _, node := range m.modulesMap {
|
for _, node := range m.ModulesMap {
|
||||||
for _, backend := range node {
|
for _, backend := range node {
|
||||||
routes = append(routes, backend)
|
routes = append(routes, backend)
|
||||||
}
|
}
|
||||||
@@ -67,7 +67,7 @@ func (m Mesh) GetRoutes() structure.RoutingConfig {
|
|||||||
|
|
||||||
func (m Mesh) CheckBackendChanged(backend structure.BackendDeclaration) (changed bool) {
|
func (m Mesh) CheckBackendChanged(backend structure.BackendDeclaration) (changed bool) {
|
||||||
address := backend.Address.GetAddress()
|
address := backend.Address.GetAddress()
|
||||||
if nodes, ok := m.modulesMap[backend.ModuleName]; ok {
|
if nodes, ok := m.ModulesMap[backend.ModuleName]; ok {
|
||||||
if oldBackend, ok := nodes[address]; ok {
|
if oldBackend, ok := nodes[address]; ok {
|
||||||
if oldBackend.Version != backend.Version || !oldBackend.IsPathsEqual(backend.Endpoints) || oldBackend.LibVersion != backend.LibVersion {
|
if oldBackend.Version != backend.Version || !oldBackend.IsPathsEqual(backend.Endpoints) || oldBackend.LibVersion != backend.LibVersion {
|
||||||
changed = true
|
changed = true
|
||||||
@@ -83,7 +83,7 @@ func (m Mesh) CheckBackendChanged(backend structure.BackendDeclaration) (changed
|
|||||||
|
|
||||||
func (m *Mesh) UpsertBackend(backend structure.BackendDeclaration) (changed bool) {
|
func (m *Mesh) UpsertBackend(backend structure.BackendDeclaration) (changed bool) {
|
||||||
address := backend.Address.GetAddress()
|
address := backend.Address.GetAddress()
|
||||||
if nodes, ok := m.modulesMap[backend.ModuleName]; ok {
|
if nodes, ok := m.ModulesMap[backend.ModuleName]; ok {
|
||||||
if oldBackend, ok := nodes[address]; ok {
|
if oldBackend, ok := nodes[address]; ok {
|
||||||
if oldBackend.Version != backend.Version || !oldBackend.IsPathsEqual(backend.Endpoints) || oldBackend.LibVersion != backend.LibVersion {
|
if oldBackend.Version != backend.Version || !oldBackend.IsPathsEqual(backend.Endpoints) || oldBackend.LibVersion != backend.LibVersion {
|
||||||
nodes[address] = backend
|
nodes[address] = backend
|
||||||
@@ -94,7 +94,7 @@ func (m *Mesh) UpsertBackend(backend structure.BackendDeclaration) (changed bool
|
|||||||
changed = true
|
changed = true
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
m.modulesMap[backend.ModuleName] = NodesMap{address: backend}
|
m.ModulesMap[backend.ModuleName] = NodesMap{address: backend}
|
||||||
changed = true
|
changed = true
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
@@ -102,18 +102,18 @@ func (m *Mesh) UpsertBackend(backend structure.BackendDeclaration) (changed bool
|
|||||||
|
|
||||||
func (m *Mesh) DeleteBackend(backend structure.BackendDeclaration) (deleted bool) {
|
func (m *Mesh) DeleteBackend(backend structure.BackendDeclaration) (deleted bool) {
|
||||||
address := backend.Address.GetAddress()
|
address := backend.Address.GetAddress()
|
||||||
if nodes, ok := m.modulesMap[backend.ModuleName]; ok {
|
if nodes, ok := m.ModulesMap[backend.ModuleName]; ok {
|
||||||
if _, ok := nodes[address]; ok {
|
if _, ok := nodes[address]; ok {
|
||||||
delete(nodes, address)
|
delete(nodes, address)
|
||||||
deleted = true
|
deleted = true
|
||||||
}
|
}
|
||||||
if len(nodes) == 0 {
|
if len(nodes) == 0 {
|
||||||
delete(m.modulesMap, backend.ModuleName)
|
delete(m.ModulesMap, backend.ModuleName)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewMesh() *Mesh {
|
func NewMesh() *Mesh {
|
||||||
return &Mesh{modulesMap: make(map[string]NodesMap)}
|
return &Mesh{ModulesMap: make(map[string]NodesMap)}
|
||||||
}
|
}
|
||||||
+15
-15
@@ -18,11 +18,11 @@ type ReadonlyModuleStore interface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type ModuleStore struct {
|
type ModuleStore struct {
|
||||||
modules []entity.Module
|
Modules []entity.Module
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ms ModuleStore) GetByName(name string) *entity.Module {
|
func (ms ModuleStore) GetByName(name string) *entity.Module {
|
||||||
for _, module := range ms.modules {
|
for _, module := range ms.Modules {
|
||||||
if module.Name == name {
|
if module.Name == name {
|
||||||
return &module
|
return &module
|
||||||
}
|
}
|
||||||
@@ -31,7 +31,7 @@ func (ms ModuleStore) GetByName(name string) *entity.Module {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (ms ModuleStore) GetById(id string) *entity.Module {
|
func (ms ModuleStore) GetById(id string) *entity.Module {
|
||||||
for _, module := range ms.modules {
|
for _, module := range ms.Modules {
|
||||||
if module.Id == id {
|
if module.Id == id {
|
||||||
return &module
|
return &module
|
||||||
}
|
}
|
||||||
@@ -40,39 +40,39 @@ func (ms ModuleStore) GetById(id string) *entity.Module {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (ms *ModuleStore) UpdateByName(module entity.Module) {
|
func (ms *ModuleStore) UpdateByName(module entity.Module) {
|
||||||
for i := range ms.modules {
|
for i := range ms.Modules {
|
||||||
if ms.modules[i].Name == module.Name {
|
if ms.Modules[i].Name == module.Name {
|
||||||
ms.modules[i] = module
|
ms.Modules[i] = module
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ms *ModuleStore) Create(module entity.Module) {
|
func (ms *ModuleStore) Create(module entity.Module) {
|
||||||
ms.modules = append(ms.modules, module)
|
ms.Modules = append(ms.Modules, module)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ms *ModuleStore) DeleteByIds(ids []string) []entity.Module {
|
func (ms *ModuleStore) DeleteByIds(ids []string) []entity.Module {
|
||||||
idsMap := StringsToMap(ids)
|
idsMap := StringsToMap(ids)
|
||||||
var deleted []entity.Module
|
var deleted []entity.Module
|
||||||
for i := 0; i < len(ms.modules); i++ {
|
for i := 0; i < len(ms.Modules); i++ {
|
||||||
id := ms.modules[i].Id
|
id := ms.Modules[i].Id
|
||||||
if _, ok := idsMap[id]; ok {
|
if _, ok := idsMap[id]; ok {
|
||||||
// change modules ordering
|
// change modules ordering
|
||||||
deleted = append(deleted, ms.modules[i])
|
deleted = append(deleted, ms.Modules[i])
|
||||||
ms.modules[i] = ms.modules[len(ms.modules)-1]
|
ms.Modules[i] = ms.Modules[len(ms.Modules)-1]
|
||||||
ms.modules = ms.modules[:len(ms.modules)-1]
|
ms.Modules = ms.Modules[:len(ms.Modules)-1]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return deleted
|
return deleted
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ms *ModuleStore) GetAll() []entity.Module {
|
func (ms *ModuleStore) GetAll() []entity.Module {
|
||||||
response := make([]entity.Module, len(ms.modules))
|
response := make([]entity.Module, len(ms.Modules))
|
||||||
copy(response, ms.modules)
|
copy(response, ms.Modules)
|
||||||
return response
|
return response
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewModuleStore() *ModuleStore {
|
func NewModuleStore() *ModuleStore {
|
||||||
return &ModuleStore{modules: make([]entity.Module, 0)}
|
return &ModuleStore{Modules: make([]entity.Module, 0)}
|
||||||
}
|
}
|
||||||
+10
-10
@@ -15,13 +15,13 @@ type ReadonlySchemaStore interface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type SchemaStore struct {
|
type SchemaStore struct {
|
||||||
schemas []entity.ConfigSchema
|
Schemas []entity.ConfigSchema
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ss SchemaStore) GetByModuleIds(ids []string) []entity.ConfigSchema {
|
func (ss SchemaStore) GetByModuleIds(ids []string) []entity.ConfigSchema {
|
||||||
idsMap := StringsToMap(ids)
|
idsMap := StringsToMap(ids)
|
||||||
result := make([]entity.ConfigSchema, 0, len(ids))
|
result := make([]entity.ConfigSchema, 0, len(ids))
|
||||||
for _, schema := range ss.schemas {
|
for _, schema := range ss.Schemas {
|
||||||
if _, ok := idsMap[schema.ModuleId]; ok {
|
if _, ok := idsMap[schema.ModuleId]; ok {
|
||||||
result = append(result, schema)
|
result = append(result, schema)
|
||||||
}
|
}
|
||||||
@@ -32,12 +32,12 @@ func (ss SchemaStore) GetByModuleIds(ids []string) []entity.ConfigSchema {
|
|||||||
func (ss *SchemaStore) DeleteByIds(ids []string) int {
|
func (ss *SchemaStore) DeleteByIds(ids []string) int {
|
||||||
idsMap := StringsToMap(ids)
|
idsMap := StringsToMap(ids)
|
||||||
var deleted int
|
var deleted int
|
||||||
for i := 0; i < len(ss.schemas); i++ {
|
for i := 0; i < len(ss.Schemas); i++ {
|
||||||
id := ss.schemas[i].Id
|
id := ss.Schemas[i].Id
|
||||||
if _, ok := idsMap[id]; ok {
|
if _, ok := idsMap[id]; ok {
|
||||||
// change schemas ordering
|
// change schemas ordering
|
||||||
ss.schemas[i] = ss.schemas[len(ss.schemas)-1]
|
ss.Schemas[i] = ss.Schemas[len(ss.Schemas)-1]
|
||||||
ss.schemas = ss.schemas[:len(ss.schemas)-1]
|
ss.Schemas = ss.Schemas[:len(ss.Schemas)-1]
|
||||||
deleted++
|
deleted++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -45,18 +45,18 @@ func (ss *SchemaStore) DeleteByIds(ids []string) int {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (ss *SchemaStore) Upsert(schema entity.ConfigSchema) entity.ConfigSchema {
|
func (ss *SchemaStore) Upsert(schema entity.ConfigSchema) entity.ConfigSchema {
|
||||||
for key, value := range ss.schemas {
|
for key, value := range ss.Schemas {
|
||||||
if value.ModuleId == schema.ModuleId {
|
if value.ModuleId == schema.ModuleId {
|
||||||
schema.Id = value.Id
|
schema.Id = value.Id
|
||||||
schema.CreatedAt = value.CreatedAt
|
schema.CreatedAt = value.CreatedAt
|
||||||
ss.schemas[key] = schema
|
ss.Schemas[key] = schema
|
||||||
return schema
|
return schema
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ss.schemas = append(ss.schemas, schema)
|
ss.Schemas = append(ss.Schemas, schema)
|
||||||
return schema
|
return schema
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSchemaStore() *SchemaStore {
|
func NewSchemaStore() *SchemaStore {
|
||||||
return &SchemaStore{schemas: make([]entity.ConfigSchema, 0)}
|
return &SchemaStore{Schemas: make([]entity.ConfigSchema, 0)}
|
||||||
}
|
}
|
||||||
+29
-29
@@ -5,51 +5,51 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type State struct {
|
type State struct {
|
||||||
mesh *Mesh
|
MeshStore *Mesh
|
||||||
configs *ConfigStore
|
ConfigsStore *ConfigStore
|
||||||
schemas *SchemaStore
|
SchemasStore *SchemaStore
|
||||||
modules *ModuleStore
|
ModulesStore *ModuleStore
|
||||||
commonConfigs *CommonConfigStore
|
CommonConfigsStore *CommonConfigStore
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s State) Mesh() ReadonlyMesh {
|
func (s State) Mesh() ReadonlyMesh {
|
||||||
return s.mesh
|
return s.MeshStore
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s State) Configs() ReadonlyConfigStore {
|
func (s State) Configs() ReadonlyConfigStore {
|
||||||
return s.configs
|
return s.ConfigsStore
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s State) Schemas() ReadonlySchemaStore {
|
func (s State) Schemas() ReadonlySchemaStore {
|
||||||
return s.schemas
|
return s.SchemasStore
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s State) Modules() ReadonlyModuleStore {
|
func (s State) Modules() ReadonlyModuleStore {
|
||||||
return s.modules
|
return s.ModulesStore
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s State) CommonConfigs() ReadonlyCommonConfigStore {
|
func (s State) CommonConfigs() ReadonlyCommonConfigStore {
|
||||||
return s.commonConfigs
|
return s.CommonConfigsStore
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *State) WritableMesh() WriteableMesh {
|
func (s *State) WritableMesh() WriteableMesh {
|
||||||
return s.mesh
|
return s.MeshStore
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *State) WritableConfigs() WriteableConfigStore {
|
func (s *State) WritableConfigs() WriteableConfigStore {
|
||||||
return s.configs
|
return s.ConfigsStore
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *State) WritableSchemas() WriteableSchemaStore {
|
func (s *State) WritableSchemas() WriteableSchemaStore {
|
||||||
return s.schemas
|
return s.SchemasStore
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *State) WritableModules() WriteableModuleStore {
|
func (s *State) WritableModules() WriteableModuleStore {
|
||||||
return s.modules
|
return s.ModulesStore
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *State) WritableCommonConfigs() WriteableCommonConfigStore {
|
func (s *State) WritableCommonConfigs() WriteableCommonConfigStore {
|
||||||
return s.commonConfigs
|
return s.CommonConfigsStore
|
||||||
}
|
}
|
||||||
|
|
||||||
type WritableState interface {
|
type WritableState interface {
|
||||||
@@ -69,22 +69,22 @@ type ReadonlyState interface {
|
|||||||
CommonConfigs() ReadonlyCommonConfigStore
|
CommonConfigs() ReadonlyCommonConfigStore
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewState() State {
|
func NewState() *State {
|
||||||
return State{
|
return &State{
|
||||||
mesh: NewMesh(),
|
MeshStore: NewMesh(),
|
||||||
configs: NewConfigStore(),
|
ConfigsStore: NewConfigStore(),
|
||||||
schemas: NewSchemaStore(),
|
SchemasStore: NewSchemaStore(),
|
||||||
modules: NewModuleStore(),
|
ModulesStore: NewModuleStore(),
|
||||||
commonConfigs: NewCommonConfigStore(),
|
CommonConfigsStore: NewCommonConfigStore(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewStateFromSnapshot(configs []entity.Config, schemas []entity.ConfigSchema, modules []entity.Module, commConfigs []entity.CommonConfig) State {
|
func NewStateFromSnapshot(configs []entity.Config, schemas []entity.ConfigSchema, modules []entity.Module, commConfigs []entity.CommonConfig) *State {
|
||||||
return State{
|
return &State{
|
||||||
mesh: NewMesh(),
|
MeshStore: NewMesh(),
|
||||||
configs: &ConfigStore{configs: configs},
|
ConfigsStore: &ConfigStore{Configs: configs},
|
||||||
schemas: &SchemaStore{schemas: schemas},
|
SchemasStore: &SchemaStore{Schemas: schemas},
|
||||||
modules: &ModuleStore{modules: modules},
|
ModulesStore: &ModuleStore{Modules: modules},
|
||||||
commonConfigs: &CommonConfigStore{configs: commConfigs},
|
CommonConfigsStore: &CommonConfigStore{Configs: commConfigs},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+4
-4
@@ -63,7 +63,7 @@ func (s *Store) Apply(l *raft.Log) interface{} {
|
|||||||
|
|
||||||
func (s *Store) Snapshot() (raft.FSMSnapshot, error) {
|
func (s *Store) Snapshot() (raft.FSMSnapshot, error) {
|
||||||
s.lock.Lock()
|
s.lock.Lock()
|
||||||
copied := deepcopy.Copy(s.state).(state.State)
|
copied := deepcopy.Copy(s.state).(*state.State)
|
||||||
s.lock.Unlock()
|
s.lock.Unlock()
|
||||||
return &fsmSnapshot{copied}, nil
|
return &fsmSnapshot{copied}, nil
|
||||||
}
|
}
|
||||||
@@ -91,7 +91,7 @@ func (s *Store) VisitState(f func(writableState state.WritableState)) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type fsmSnapshot struct {
|
type fsmSnapshot struct {
|
||||||
state state.State
|
state *state.State
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *fsmSnapshot) Persist(sink raft.SnapshotSink) error {
|
func (f *fsmSnapshot) Persist(sink raft.SnapshotSink) error {
|
||||||
@@ -114,9 +114,9 @@ func (f *fsmSnapshot) Persist(sink raft.SnapshotSink) error {
|
|||||||
|
|
||||||
func (f *fsmSnapshot) Release() {}
|
func (f *fsmSnapshot) Release() {}
|
||||||
|
|
||||||
func NewStateStore(st state.State) *Store {
|
func NewStateStore(st *state.State) *Store {
|
||||||
store := &Store{
|
store := &Store{
|
||||||
state: &st,
|
state: st,
|
||||||
}
|
}
|
||||||
store.handlers = map[uint64]func([]byte) (interface{}, error){
|
store.handlers = map[uint64]func([]byte) (interface{}, error){
|
||||||
cluster.UpdateBackendDeclarationCommand: store.applyUpdateBackendDeclarationCommand,
|
cluster.UpdateBackendDeclarationCommand: store.applyUpdateBackendDeclarationCommand,
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"isp-config-service/entity"
|
||||||
|
state2 "isp-config-service/store/state"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type mockSnapshotSink struct {
|
||||||
|
bytes.Buffer
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d mockSnapshotSink) Close() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d mockSnapshotSink) ID() string {
|
||||||
|
panic("implement me")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d mockSnapshotSink) Cancel() error {
|
||||||
|
panic("implement me")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStore_SnapshotRestore(t *testing.T) {
|
||||||
|
state := state2.NewState()
|
||||||
|
state.WritableModules().Create(entity.Module{
|
||||||
|
Id: state2.GenerateId(),
|
||||||
|
Name: "name1",
|
||||||
|
CreatedAt: time.Now().Round(time.Millisecond),
|
||||||
|
LastConnectedAt: time.Now().Round(time.Millisecond),
|
||||||
|
LastDisconnectedAt: time.Now().Round(time.Millisecond),
|
||||||
|
})
|
||||||
|
|
||||||
|
store := NewStateStore(state)
|
||||||
|
snapshot, err := store.Snapshot()
|
||||||
|
assert.NoError(t, err)
|
||||||
|
sink := mockSnapshotSink{}
|
||||||
|
err = snapshot.Persist(&sink)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
|
||||||
|
newState := state2.NewState()
|
||||||
|
store.state = newState
|
||||||
|
err = store.Restore(&sink)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
|
||||||
|
assert.Equal(t, state, store.state)
|
||||||
|
}
|
||||||
+7
-8
@@ -15,7 +15,7 @@ import (
|
|||||||
"isp-config-service/store/state"
|
"isp-config-service/store/state"
|
||||||
)
|
)
|
||||||
|
|
||||||
func (h *socketEventHandler) handleModuleReady(conn etp.Conn, data []byte) []byte {
|
func (h *SocketEventHandler) handleModuleReady(conn etp.Conn, data []byte) []byte {
|
||||||
moduleName, _ := Parameters(conn) // REMOVE
|
moduleName, _ := Parameters(conn) // REMOVE
|
||||||
log.Debugf(0, "handleModuleReady moduleName: %s", moduleName) // REMOVE
|
log.Debugf(0, "handleModuleReady moduleName: %s", moduleName) // REMOVE
|
||||||
declaration := structure.BackendDeclaration{}
|
declaration := structure.BackendDeclaration{}
|
||||||
@@ -37,7 +37,7 @@ func (h *socketEventHandler) handleModuleReady(conn etp.Conn, data []byte) []byt
|
|||||||
return []byte(utils.WsOkResponse)
|
return []byte(utils.WsOkResponse)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *socketEventHandler) handleModuleRequirements(conn etp.Conn, data []byte) []byte {
|
func (h *SocketEventHandler) handleModuleRequirements(conn etp.Conn, data []byte) []byte {
|
||||||
moduleName, err := Parameters(conn)
|
moduleName, err := Parameters(conn)
|
||||||
log.Debugf(0, "handleModuleRequirements moduleName: %s", moduleName) // REMOVE
|
log.Debugf(0, "handleModuleRequirements moduleName: %s", moduleName) // REMOVE
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -59,7 +59,7 @@ func (h *socketEventHandler) handleModuleRequirements(conn etp.Conn, data []byte
|
|||||||
return []byte(utils.WsOkResponse)
|
return []byte(utils.WsOkResponse)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *socketEventHandler) handleConfigSchema(conn etp.Conn, data []byte) []byte {
|
func (h *SocketEventHandler) handleConfigSchema(conn etp.Conn, data []byte) []byte {
|
||||||
moduleName, err := Parameters(conn)
|
moduleName, err := Parameters(conn)
|
||||||
log.Debugf(0, "handleConfigSchema moduleName: %s", moduleName) // REMOVE
|
log.Debugf(0, "handleConfigSchema moduleName: %s", moduleName) // REMOVE
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -95,7 +95,10 @@ func (h *socketEventHandler) handleConfigSchema(conn etp.Conn, data []byte) []by
|
|||||||
h.store.VisitReadonlyState(func(readState state.ReadonlyState) {
|
h.store.VisitReadonlyState(func(readState state.ReadonlyState) {
|
||||||
configs = readState.Configs().GetByModuleIds([]string{module.Id})
|
configs = readState.Configs().GetByModuleIds([]string{module.Id})
|
||||||
})
|
})
|
||||||
if len(configs) == 0 && len(configSchema.DefaultConfig) > 0 {
|
if len(configs) == 0 { //create empty default config
|
||||||
|
if configSchema.DefaultConfig == nil {
|
||||||
|
configSchema.DefaultConfig = make(map[string]interface{})
|
||||||
|
}
|
||||||
config := entity.Config{
|
config := entity.Config{
|
||||||
Id: state.GenerateId(),
|
Id: state.GenerateId(),
|
||||||
Name: module.Name,
|
Name: module.Name,
|
||||||
@@ -115,7 +118,3 @@ func (h *socketEventHandler) handleConfigSchema(conn etp.Conn, data []byte) []by
|
|||||||
}
|
}
|
||||||
return []byte(utils.WsOkResponse)
|
return []byte(utils.WsOkResponse)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *socketEventHandler) handleRequestConfig(conn etp.Conn, data []byte) []byte {
|
|
||||||
panic("not implemented")
|
|
||||||
}
|
|
||||||
+1
-1
@@ -8,7 +8,7 @@ import (
|
|||||||
"isp-config-service/holder"
|
"isp-config-service/holder"
|
||||||
)
|
)
|
||||||
|
|
||||||
func (h *socketEventHandler) applyCommandOnLeader(_ etp.Conn, cmd []byte) []byte {
|
func (h *SocketEventHandler) applyCommandOnLeader(_ etp.Conn, cmd []byte) []byte {
|
||||||
cmdCopy := make([]byte, len(cmd))
|
cmdCopy := make([]byte, len(cmd))
|
||||||
copy(cmdCopy, cmd)
|
copy(cmdCopy, cmd)
|
||||||
obj, err := holder.ClusterClient.SyncApplyOnLeader(cmdCopy)
|
obj, err := holder.ClusterClient.SyncApplyOnLeader(cmdCopy)
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ type connectionState struct {
|
|||||||
func IsConfigClusterNode(conn etp.Conn) bool {
|
func IsConfigClusterNode(conn etp.Conn) bool {
|
||||||
isCluster := conn.URL().Query().Get(cluster.ClusterParam)
|
isCluster := conn.URL().Query().Get(cluster.ClusterParam)
|
||||||
return isCluster == "true"
|
return isCluster == "true"
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func Parameters(conn etp.Conn) (moduleName string, err error) {
|
func Parameters(conn etp.Conn) (moduleName string, err error) {
|
||||||
|
|||||||
+7
-7
@@ -18,12 +18,12 @@ var (
|
|||||||
json = jsoniter.ConfigFastest
|
json = jsoniter.ConfigFastest
|
||||||
)
|
)
|
||||||
|
|
||||||
type socketEventHandler struct {
|
type SocketEventHandler struct {
|
||||||
server etp.Server
|
server etp.Server
|
||||||
store *store.Store
|
store *store.Store
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *socketEventHandler) SubscribeAll() {
|
func (h *SocketEventHandler) SubscribeAll() {
|
||||||
h.server.
|
h.server.
|
||||||
OnConnect(h.handleConnect).
|
OnConnect(h.handleConnect).
|
||||||
OnDisconnect(h.handleDisconnect).
|
OnDisconnect(h.handleDisconnect).
|
||||||
@@ -34,7 +34,7 @@ func (h *socketEventHandler) SubscribeAll() {
|
|||||||
OnWithAck(utils.ModuleSendConfigSchema, h.handleConfigSchema)
|
OnWithAck(utils.ModuleSendConfigSchema, h.handleConfigSchema)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *socketEventHandler) handleConnect(conn etp.Conn) {
|
func (h *SocketEventHandler) handleConnect(conn etp.Conn) {
|
||||||
isClusterNode := IsConfigClusterNode(conn)
|
isClusterNode := IsConfigClusterNode(conn)
|
||||||
moduleName, err := Parameters(conn)
|
moduleName, err := Parameters(conn)
|
||||||
log.Debugf(0, "handleConnect: %s", moduleName) // REMOVE
|
log.Debugf(0, "handleConnect: %s", moduleName) // REMOVE
|
||||||
@@ -79,7 +79,7 @@ func (h *socketEventHandler) handleConnect(conn etp.Conn) {
|
|||||||
EmitConn(conn, utils.ConfigSendConfigWhenConnected, data)
|
EmitConn(conn, utils.ConfigSendConfigWhenConnected, data)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *socketEventHandler) handleDisconnect(conn etp.Conn, disconnectErr error) {
|
func (h *SocketEventHandler) handleDisconnect(conn etp.Conn, disconnectErr error) {
|
||||||
moduleName, _ := Parameters(conn)
|
moduleName, _ := Parameters(conn)
|
||||||
log.Debugf(0, "handleDisconnect: %s", moduleName) // REMOVE
|
log.Debugf(0, "handleDisconnect: %s", moduleName) // REMOVE
|
||||||
if moduleName != "" {
|
if moduleName != "" {
|
||||||
@@ -105,12 +105,12 @@ func (h *socketEventHandler) handleDisconnect(conn etp.Conn, disconnectErr error
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *socketEventHandler) handleError(_ etp.Conn, err error) {
|
func (h *SocketEventHandler) handleError(_ etp.Conn, err error) {
|
||||||
log.Warnf(codes.WebsocketError, "isp-etp: %v", err)
|
log.Warnf(codes.WebsocketError, "isp-etp: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSocketEventHandler(server etp.Server, store *store.Store) *socketEventHandler {
|
func NewSocketEventHandler(server etp.Server, store *store.Store) *SocketEventHandler {
|
||||||
return &socketEventHandler{
|
return &SocketEventHandler{
|
||||||
server: server,
|
server: server,
|
||||||
store: store,
|
store: store,
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user