Compare commits

..
9 Commits
36 changed files with 388 additions and 593 deletions

No files matched your search

+1 -1
View File
@@ -1 +1 @@
2.0.3
2.1.1
+8
View File
@@ -1,3 +1,11 @@
### 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
* fix data race when applyCommandOnLeader in websocket handler
* update dependencies
Generated
+12 -5
View File
@@ -277,10 +277,9 @@
version = "v2.0.2"
[[projects]]
digest = "1:d30832edf4ae7a45e863e216c89bb5f1d66c10ff5b3255b9e007598a048594d7"
digest = "1:194932f6894a42dd62acd1092c529befbe576abf50fe929a0e30ae3544ceb6ee"
name = "github.com/integration-system/isp-lib"
packages = [
"atomic",
"backend",
"bootstrap",
"config",
@@ -293,8 +292,8 @@
"utils",
]
pruneopts = "UT"
revision = "abfa9a9776d64e6d04d495bfe00db8ca4dcbe7fc"
version = "v2.0.1"
revision = "4ea9449f1b3f2565b9038b0d4cdda3b02089aa8c"
version = "v2.1.0"
[[projects]]
digest = "1:1562269205ab0c6685c8b0b99511e91b9d3627e4cac3f0288378bc8930e658f1"
@@ -328,6 +327,14 @@
pruneopts = "UT"
revision = "5475a8b08e62e41fa886641861ac225e7f91e4e5"
[[projects]]
digest = "1:965f8051786df58d7d62c8ffa2d90cb84000aab1a167e5c4713ff572cd7e164e"
name = "github.com/integration-system/net-mux"
packages = ["."]
pruneopts = "UT"
revision = "9dc223fe46d293b528c8e2a04c43d991bc23a2de"
version = "v1.0.0"
[[projects]]
digest = "1:01ed62f8f4f574d8aff1d88caee113700a2b44c42351943fa73cc1808f736a50"
name = "github.com/jinzhu/inflection"
@@ -756,7 +763,6 @@
"github.com/integration-system/isp-lib-test/docker",
"github.com/integration-system/isp-lib-test/utils",
"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/bootstrap",
"github.com/integration-system/isp-lib/config",
@@ -766,6 +772,7 @@
"github.com/integration-system/isp-lib/utils",
"github.com/integration-system/isp-log",
"github.com/integration-system/isp-log/stdcodes",
"github.com/integration-system/net-mux",
"github.com/json-iterator/go",
"github.com/mohae/deepcopy",
"github.com/pkg/errors",
+2 -2
View File
@@ -54,8 +54,8 @@ func PrepareDeleteModulesCommand(ids []string) []byte {
return prepareCommand(DeleteModulesCommand, DeleteModules{Ids: ids})
}
func PrepareActivateConfigCommand(configId string, date time.Time) []byte {
return prepareCommand(ActivateConfigCommand, ActivateConfig{ConfigId: configId, Date: date})
func PrepareActivateConfigCommand(configID string, date time.Time) []byte {
return prepareCommand(ActivateConfigCommand, ActivateConfig{ConfigId: configID, Date: date})
}
func PrepareDeleteConfigsCommand(ids []string) []byte {
+2 -2
View File
@@ -68,7 +68,7 @@ func NewSocketLeaderClient(address string, leaderDisconnectionCallback func()) *
client := etp.NewClient(etpConfig)
leaderClient := &SocketLeaderClient{
client: client,
url: getUrl(address),
url: getURL(address),
}
ctx, cancel := context.WithCancel(context.Background())
leaderClient.globalCtx = ctx
@@ -90,7 +90,7 @@ func NewSocketLeaderClient(address string, leaderDisconnectionCallback func()) *
return leaderClient
}
func getUrl(address string) string {
func getURL(address string) string {
addr, err := net.ResolveTCPAddr("tcp", address)
if err != nil {
panic(err) // must never occurred
+1 -1
View File
@@ -15,8 +15,8 @@ type Configuration struct {
type ClusterConfiguration struct {
InMemory bool `schema:"Хранить логи и снэпшоты только в памяти"`
DataDir string `valid:"required~Required" schema:"Пусть до директории для логов и снэпшотов рафта"`
BootstrapCluster bool `schema:"Поднимать кластер и объявлять лидером"`
DataDir string `valid:"required~Required" schema:"Пусть до директории для логов и снэпшотов рафта"`
Peers []string `valid:"required~Required" schema:"Адреса всех нод в кластере,формат address:port"`
OuterAddress string `valid:"required~Required" schema:"Внешний адрес ноды"`
ConnectTimeoutSeconds int `valid:"required~Required" schema:"Таймаут подключения"`
+30 -15
View File
@@ -2,6 +2,7 @@ package main
import (
"bytes"
"errors"
"fmt"
"github.com/integration-system/isp-lib-test/ctx"
"github.com/integration-system/isp-lib-test/docker"
@@ -30,6 +31,7 @@ const (
configsNumber = 3
maxAwaitingTime = 25 * time.Second
attemptTimeout = 300 * time.Millisecond
deleteCommonConfigsCommand = "config/common_config/delete_config"
getRoutesCommand = "config/routing/get_routes"
@@ -109,6 +111,7 @@ func setup(testCtx *ctx.TestContext, runTest func() int) int {
cfg.Images.Module, c, nil,
docker.WithName(c.GrpcOuterAddress.IP),
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.WithEnv(peersAddrsEnv),
)
@@ -169,8 +172,8 @@ func TestClusterElection(t *testing.T) {
}
func getConfigServiceAddress(num int, port string) structure.AddressConfiguration {
lastIp := pgCfg.Address
ip := net.ParseIP(lastIp).To4()
lastIP := pgCfg.Address
ip := net.ParseIP(lastIP).To4()
ip[3] = byte(int(ip[3]) + num + 1)
return structure.AddressConfiguration{
//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)
return nil, err
}, maxAwaitingTime)
}, maxAwaitingTime, attemptTimeout)
if !a.NoError(err) {
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
}
@@ -257,27 +260,39 @@ func testRaftReady(client *backend.InternalGrpcClient, a *assert.Assertions) boo
//log.Println("send grpc request. response: ", response, "err: ", err)
return nil, err
}
_, _ = await(f, maxAwaitingTime)
log.Println("waiting until raft ready:", time.Now().Sub(start).Round(time.Second))
_, _ = await(f, maxAwaitingTime, attemptTimeout)
log.Println("waiting until raft ready:", time.Since(start).Round(time.Second))
return a.NoError(err)
}
func getRoutes(client *backend.InternalGrpcClient, a *assert.Assertions) []structure.BackendDeclaration {
var response []structure.BackendDeclaration
err := client.Invoke(
getRoutesCommand,
-1,
nil,
&response,
)
//log.Println("routes:", response)
var err error
f := func() (interface{}, error) {
err = client.Invoke(
getRoutesCommand,
-1,
nil,
&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)
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.AttemptTimeout = 300 * time.Millisecond
retryer.AttemptTimeout = attemptTimeout
return retryer.Do()
}
+12 -6
View File
@@ -29,17 +29,23 @@ type config struct {
// @Failure 500 {object} structure.GrpcError
// @Router /config/get_active_config_by_module_name [POST]
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) {
module := state.Modules().GetByName(request.ModuleName)
module = state.Modules().GetByName(request.ModuleName)
if module != nil {
response = state.Configs().GetActiveByModuleId(module.Id)
config = state.Configs().GetActiveByModuleId(module.Id)
}
})
if response == nil {
return nil, status.Error(codes.NotFound, utils.ValidationError)
if module == nil {
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
+24
View File
@@ -1,8 +1,10 @@
package controller
import (
"google.golang.org/grpc/status"
"isp-config-service/cluster"
"isp-config-service/domain"
"isp-config-service/entity"
"isp-config-service/service"
"isp-config-service/store"
"isp-config-service/store/state"
@@ -61,6 +63,28 @@ func (*module) DeleteModules(identities []string) (*domain.DeleteResponse, error
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 {
return &module{
rstore: rstore,
+65 -17
View File
@@ -63,7 +63,7 @@ definitions:
type: object
endpoints:
items:
$ref: '#/definitions/structure.EndpointConfig'
$ref: '#/definitions/structure.EndpointDescriptor'
type: array
establishedAt:
type: string
@@ -223,6 +223,21 @@ definitions:
version:
type: string
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:
additionalProperties: {}
type: object
@@ -236,7 +251,7 @@ definitions:
type: string
additionalItems:
description: section 5.9
type: integer
type: string
additionalProperties:
description: section 5.18
type: string
@@ -281,7 +296,7 @@ definitions:
type: string
items:
description: section 5.9
type: integer
type: string
maxItems:
description: section 5.10
type: integer
@@ -296,7 +311,7 @@ definitions:
type: integer
media:
description: RFC draft-wright-json-schema-hyperschema-00, section 4
type: integer
type: string
minItems:
description: section 5.11
type: integer
@@ -314,7 +329,7 @@ definitions:
type: integer
not:
description: section 5.25
type: integer
type: string
oneOf:
description: section 5.24
items:
@@ -354,7 +369,7 @@ definitions:
type: string
additionalItems:
description: section 5.9
type: integer
type: string
additionalProperties:
description: section 5.18
type: string
@@ -400,7 +415,7 @@ definitions:
type: string
items:
description: section 5.9
type: integer
type: string
maxItems:
description: section 5.10
type: integer
@@ -415,7 +430,7 @@ definitions:
type: integer
media:
description: RFC draft-wright-json-schema-hyperschema-00, section 4
type: integer
type: string
minItems:
description: section 5.11
type: integer
@@ -433,7 +448,7 @@ definitions:
type: integer
not:
description: section 5.25
type: integer
type: string
oneOf:
description: section 5.24
items:
@@ -473,7 +488,7 @@ definitions:
type: string
additionalItems:
description: section 5.9
type: integer
type: string
additionalProperties:
description: section 5.18
type: string
@@ -518,7 +533,7 @@ definitions:
type: string
items:
description: section 5.9
type: integer
type: string
maxItems:
description: section 5.10
type: integer
@@ -533,7 +548,7 @@ definitions:
type: integer
media:
description: RFC draft-wright-json-schema-hyperschema-00, section 4
type: integer
type: string
minItems:
description: section 5.11
type: integer
@@ -551,7 +566,7 @@ definitions:
type: integer
not:
description: section 5.25
type: integer
type: string
oneOf:
description: section 5.24
items:
@@ -595,7 +610,7 @@ definitions:
type: object
endpoints:
items:
$ref: '#/definitions/structure.EndpointConfig'
$ref: '#/definitions/structure.EndpointDescriptor'
type: array
libVersion:
type: string
@@ -604,14 +619,16 @@ definitions:
version:
type: string
type: object
structure.EndpointConfig:
structure.EndpointDescriptor:
properties:
ignoreOnRouter:
type: boolean
extra:
type: object
inner:
type: boolean
path:
type: string
userAuthRequired:
type: boolean
required:
- path
type: object
@@ -915,6 +932,37 @@ paths:
summary: Метод удаления объектов модулей по идентификаторам
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:
post:
consumes:
+1 -1
View File
@@ -27,7 +27,7 @@ type Connection struct {
LibVersion string
Version string
Address structure.AddressConfiguration
Endpoints []structure.EndpointConfig `json:",omitempty"`
Endpoints []structure.EndpointDescriptor `json:",omitempty"`
EstablishedAt time.Time
}
+6 -5
View File
@@ -9,9 +9,9 @@ import (
type Handlers struct {
// ===== MODULE =====
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"`
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"`
GetModuleByName func(req domain.GetByModuleNameRequest) (*entity.Module, error) `method:"get_by_name" group:"module" inner:"true"`
// ===== CONFIG =====
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"`
@@ -34,8 +34,9 @@ type Handlers struct {
func GetHandlers() *Handlers {
return &Handlers{
DeleteModules: controller.Module.DeleteModules,
GetModulesInfo: controller.Module.GetModulesAggregatedInfo,
DeleteModules: controller.Module.DeleteModules,
GetModulesInfo: controller.Module.GetModulesAggregatedInfo,
GetModuleByName: controller.Module.GetModuleByName,
GetActiveConfigByModuleName: controller.Config.GetActiveConfigByModuleName,
CreateUpdateConfig: controller.Config.CreateUpdateConfig,
+1 -1
View File
@@ -9,5 +9,5 @@ import (
var (
ClusterClient *cluster.Client
EtpServer etp.Server
HttpServer *http.Server
HTTPServer *http.Server
)
+9 -6
View File
@@ -10,6 +10,7 @@ import (
"github.com/integration-system/isp-lib/structure"
"github.com/integration-system/isp-lib/utils"
log "github.com/integration-system/isp-log"
mux "github.com/integration-system/net-mux"
"github.com/thecodeteam/goodbye"
"isp-config-service/cluster"
"isp-config-service/codes"
@@ -18,7 +19,6 @@ import (
"isp-config-service/helper"
"isp-config-service/holder"
"isp-config-service/model"
"isp-config-service/mux"
"isp-config-service/raft"
"isp-config-service/service"
"isp-config-service/store"
@@ -57,6 +57,9 @@ func init() {
// @host localhost:9003
// @BasePath /api/config
//go:generate swag init --parseVendor
//go:generate rm -f docs/docs.go docs/swagger.json
func main() {
ctx := context.Background()
cfg := config.Get().(*conf.Configuration)
@@ -64,7 +67,7 @@ func main() {
endpoints := backend.GetEndpoints(cfg.ModuleName, handlers)
address := cfg.GrpcOuterAddress
if address.IP == "" {
ip, err := getOutboundIp()
ip, err := getOutboundIP()
if err != nil {
panic(err)
}
@@ -139,7 +142,7 @@ func initWebsocket(ctx context.Context, wsConnectionReadLimitKB int64, listener
}
}()
holder.EtpServer = etpServer
holder.HttpServer = httpServer
holder.HTTPServer = httpServer
}
func initRaft(listener net.Listener, clusterCfg conf.ClusterConfiguration, declaration structure.BackendDeclaration) (*cluster.Client, *store.Store) {
@@ -159,7 +162,7 @@ func initRaft(listener net.Listener, clusterCfg conf.ClusterConfiguration, decla
cfg := config.Get().(*conf.Configuration)
addr, err := net.ResolveTCPAddr("tcp", address)
if err != nil {
panic(err) // must never occured
panic(err) // must never occurred
}
port := cfg.GrpcOuterAddress.Port
addressConfiguration := structure.AddressConfiguration{Port: port, IP: addr.IP.String()}
@@ -196,7 +199,7 @@ func onShutdown(ctx context.Context, _ os.Signal) {
backend.StopGrpcServer()
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)
} else {
log.Info(codes.ShutdownHttpServerInfo, "http server shutdown success")
@@ -211,7 +214,7 @@ func onShutdown(ctx context.Context, _ os.Signal) {
_ = muxer.Close()
}
func getOutboundIp() (string, error) {
func getOutboundIP() (string, error) {
conn, err := net.Dial("udp", "9.9.9.9:80")
if err != nil {
return "", err
-44
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -17,8 +17,8 @@ const (
)
type ChangeLeaderNotification struct {
IsLeader bool
CurrentLeaderAddress string
IsLeader bool
LeaderElected bool
}
@@ -55,11 +55,13 @@ func (r *Raft) LeaderCh() <-chan ChangeLeaderNotification {
func (r *Raft) GracefulShutdown() error {
r.r.DeregisterObserver(r.leaderObs)
close(r.closer)
close(r.changeLeaderCh)
close(r.leaderObsCh)
return r.r.Shutdown().Error()
}
func (r *Raft) listenLeader() {
defer close(r.changeLeaderCh)
for {
select {
case _, ok := <-r.leaderObsCh:
@@ -73,6 +75,8 @@ func (r *Raft) listenLeader() {
CurrentLeaderAddress: string(currentLeader),
LeaderElected: currentLeader != "",
}:
case <-r.closer:
return
default:
continue
}
+2 -2
View File
@@ -73,8 +73,8 @@ func (s commonConfigService) HandleUpsertConfigCommand(upsertConfig cluster.Upse
return cluster.NewResponse(config)
}
func (s commonConfigService) GetCommonConfigLinks(commonConfigId string, state state.ReadonlyState) domain.CommonConfigLinks {
configs := state.Configs().FilterByCommonConfigs([]string{commonConfigId})
func (s commonConfigService) GetCommonConfigLinks(commonConfigID string, state state.ReadonlyState) domain.CommonConfigLinks {
configs := state.Configs().FilterByCommonConfigs([]string{commonConfigID})
result := make(domain.CommonConfigLinks)
for _, c := range configs {
module := state.Modules().GetById(c.ModuleId)
+2 -2
View File
@@ -158,8 +158,8 @@ func (cs configService) HandleUpsertConfigCommand(upsertConfig cluster.UpsertCon
func (cs configService) BroadcastNewConfig(state state.ReadonlyState, configs ...entity.Config) {
for _, cfg := range configs {
moduleId := cfg.ModuleId
module := state.Modules().GetById(moduleId)
moduleID := cfg.ModuleId
module := state.Modules().GetById(moduleID)
moduleName := module.Name
room := moduleName + ConfigWatchersRoomSuffix
+19 -19
View File
@@ -24,12 +24,12 @@ type discoveryService struct {
lock sync.RWMutex
}
func (ds *discoveryService) HandleDisconnect(connId string) {
func (ds *discoveryService) HandleDisconnect(connID string) {
ds.lock.Lock()
defer ds.lock.Unlock()
if events, ok := ds.subs[connId]; ok {
holder.EtpServer.Rooms().LeaveByConnId(connId, events...)
delete(ds.subs, connId)
if events, ok := ds.subs[connID]; ok {
holder.EtpServer.Rooms().LeaveByConnId(connID, events...)
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 {
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
} else {
err = holder.EtpServer.BroadcastToRoom(room, event, bytes)
if err != nil {
return err
}
}
return nil
}
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
} 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
}
+8 -8
View File
@@ -22,8 +22,8 @@ var RoutesService routesService
type routesService struct{}
func (rs *routesService) HandleDisconnect(connId string) {
holder.EtpServer.Rooms().LeaveByConnId(connId, RoutesSubscribersRoom)
func (rs *routesService) HandleDisconnect(connID string) {
holder.EtpServer.Rooms().LeaveByConnId(connID, RoutesSubscribersRoom)
}
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 {
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
} else {
err = holder.EtpServer.BroadcastToRoom(RoutesSubscribersRoom, event, bytes)
if err != nil {
return err
}
}
return nil
}
+5 -5
View File
@@ -6,22 +6,22 @@ import (
"isp-config-service/store/state"
)
func NewStateFromRepository() (state.State, error) {
func NewStateFromRepository() (*state.State, error) {
configs, err := model.ConfigRep.Snapshot()
if err != nil {
return state.State{}, errors.WithMessage(err, "restore configs")
return nil, errors.WithMessage(err, "restore configs")
}
schemas, err := model.SchemaRep.Snapshot()
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()
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()
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)
+14 -14
View File
@@ -18,13 +18,13 @@ type ReadonlyCommonConfigStore interface {
}
type CommonConfigStore struct {
configs []entity.CommonConfig
Configs []entity.CommonConfig
}
func (cs CommonConfigStore) GetByIds(ids []string) []entity.CommonConfig {
idsMap := StringsToMap(ids)
configs := make([]entity.CommonConfig, 0, len(ids))
for _, config := range cs.configs {
for _, config := range cs.Configs {
if _, found := idsMap[config.Id]; found {
configs = append(configs, config)
}
@@ -34,7 +34,7 @@ func (cs CommonConfigStore) GetByIds(ids []string) []entity.CommonConfig {
func (cs CommonConfigStore) GetByName(name string) []entity.CommonConfig {
configs := make([]entity.CommonConfig, 0)
for _, config := range cs.configs {
for _, config := range cs.Configs {
if config.Name == name {
configs = append(configs, config)
}
@@ -49,14 +49,14 @@ func (cs *CommonConfigStore) Create(config entity.CommonConfig) entity.CommonCon
if config.Data == nil {
config.Data = make(entity.ConfigData)
}
cs.configs = append(cs.configs, config)
cs.Configs = append(cs.Configs, config)
return config
}
func (cs *CommonConfigStore) UpdateById(config entity.CommonConfig) {
for i := range cs.configs {
if cs.configs[i].Id == config.Id {
cs.configs[i] = config
for i := range cs.Configs {
if cs.Configs[i].Id == config.Id {
cs.Configs[i] = config
break
}
}
@@ -65,12 +65,12 @@ func (cs *CommonConfigStore) UpdateById(config entity.CommonConfig) {
func (cs *CommonConfigStore) DeleteByIds(ids []string) int {
idsMap := StringsToMap(ids)
var deleted int
for i := 0; i < len(cs.configs); i++ {
id := cs.configs[i].Id
for i := 0; i < len(cs.Configs); i++ {
id := cs.Configs[i].Id
if _, ok := idsMap[id]; ok {
// change configs ordering
cs.configs[i] = cs.configs[len(cs.configs)-1]
cs.configs = cs.configs[:len(cs.configs)-1]
cs.Configs[i] = cs.Configs[len(cs.Configs)-1]
cs.Configs = cs.Configs[:len(cs.Configs)-1]
deleted++
}
}
@@ -78,11 +78,11 @@ func (cs *CommonConfigStore) DeleteByIds(ids []string) int {
}
func (cs *CommonConfigStore) GetAll() []entity.CommonConfig {
response := make([]entity.CommonConfig, len(cs.configs))
copy(response, cs.configs)
response := make([]entity.CommonConfig, len(cs.Configs))
copy(response, cs.Configs)
return response
}
func NewCommonConfigStore() *CommonConfigStore {
return &CommonConfigStore{configs: make([]entity.CommonConfig, 0)}
return &CommonConfigStore{Configs: make([]entity.CommonConfig, 0)}
}
+23 -23
View File
@@ -25,11 +25,11 @@ type ReadonlyConfigStore interface {
}
type ConfigStore struct {
configs []entity.Config
Configs []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 {
return &conf
}
@@ -40,7 +40,7 @@ func (cs ConfigStore) GetActiveByModuleId(moduleId string) *entity.Config {
func (cs ConfigStore) GetByIds(ids []string) []entity.Config {
idsMap := StringsToMap(ids)
result := make([]entity.Config, 0, len(ids))
for _, conf := range cs.configs {
for _, conf := range cs.Configs {
if _, ok := idsMap[conf.Id]; ok {
result = append(result, conf)
}
@@ -51,7 +51,7 @@ func (cs ConfigStore) GetByIds(ids []string) []entity.Config {
func (cs ConfigStore) GetByModuleIds(ids []string) []entity.Config {
idsMap := StringsToMap(ids)
result := make([]entity.Config, 0, len(ids))
for _, conf := range cs.configs {
for _, conf := range cs.Configs {
if _, ok := idsMap[conf.ModuleId]; ok {
result = append(result, conf)
}
@@ -73,14 +73,14 @@ func (cs *ConfigStore) Create(config entity.Config) entity.Config {
if config.CommonConfigs == nil {
config.CommonConfigs = make([]string, 0)
}
cs.configs = append(cs.configs, config)
cs.Configs = append(cs.Configs, config)
return config
}
func (cs *ConfigStore) UpdateById(config entity.Config) {
for i := range cs.configs {
if cs.configs[i].Id == config.Id {
cs.configs[i] = config
for i := range cs.Configs {
if cs.Configs[i].Id == config.Id {
cs.Configs[i] = config
break
}
}
@@ -88,10 +88,10 @@ func (cs *ConfigStore) UpdateById(config entity.Config) {
func (cs *ConfigStore) calcNewVersion(moduleId string) int32 {
var maxVersion int32 = 0
for i := range cs.configs {
if cs.configs[i].ModuleId == moduleId {
if cs.configs[i].Version > maxVersion {
maxVersion = cs.configs[i].Version
for i := range cs.Configs {
if cs.Configs[i].ModuleId == moduleId {
if cs.Configs[i].Version > maxVersion {
maxVersion = cs.Configs[i].Version
}
}
}
@@ -101,12 +101,12 @@ func (cs *ConfigStore) calcNewVersion(moduleId string) int32 {
func (cs *ConfigStore) DeleteByIds(ids []string) int {
idsMap := StringsToMap(ids)
var deleted int
for i := 0; i < len(cs.configs); i++ {
id := cs.configs[i].Id
for i := 0; i < len(cs.Configs); i++ {
id := cs.Configs[i].Id
if _, ok := idsMap[id]; ok {
// change configs ordering
cs.configs[i] = cs.configs[len(cs.configs)-1]
cs.configs = cs.configs[:len(cs.configs)-1]
cs.Configs[i] = cs.Configs[len(cs.Configs)-1]
cs.Configs = cs.Configs[:len(cs.Configs)-1]
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 {
affected := make([]entity.Config, 0)
for i := range cs.configs {
if cs.configs[i].ModuleId == moduleId && cs.configs[i].Active {
cs.configs[i].Active = false
cs.configs[i].UpdatedAt = date
affected = append(affected, cs.configs[i])
for i := range cs.Configs {
if cs.Configs[i].ModuleId == moduleId && cs.Configs[i].Active {
cs.Configs[i].Active = false
cs.Configs[i].UpdatedAt = date
affected = append(affected, cs.Configs[i])
}
}
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 {
idsMap := StringsToMap(commonIds)
result := make([]entity.Config, 0)
for _, cfg := range cs.configs {
for _, cfg := range cs.Configs {
for _, commonId := range cfg.CommonConfigs {
if _, ok := idsMap[commonId]; ok {
result = append(result, cfg)
@@ -149,5 +149,5 @@ func (cs *ConfigStore) FilterByCommonConfigs(commonIds []string) []entity.Config
}
func NewConfigStore() *ConfigStore {
return &ConfigStore{configs: make([]entity.Config, 0)}
return &ConfigStore{Configs: make([]entity.Config, 0)}
}
+11 -11
View File
@@ -22,12 +22,12 @@ type NodesMap map[string]structure.BackendDeclaration
type Mesh struct {
// { "ModuleName": { "address": BackendDeclaration, ...}, ... }
modulesMap map[string]NodesMap
ModulesMap map[string]NodesMap
}
func (m Mesh) BackendExist(backend structure.BackendDeclaration) (exist bool) {
address := backend.Address.GetAddress()
if nodes, ok := m.modulesMap[backend.ModuleName]; ok {
if nodes, ok := m.ModulesMap[backend.ModuleName]; ok {
if _, ok := nodes[address]; ok {
exist = true
}
@@ -37,7 +37,7 @@ func (m Mesh) BackendExist(backend structure.BackendDeclaration) (exist bool) {
func (m Mesh) GetBackends(module string) []structure.BackendDeclaration {
declarations := make([]structure.BackendDeclaration, 0)
if nodes, ok := m.modulesMap[module]; ok {
if nodes, ok := m.ModulesMap[module]; ok {
for _, backend := range nodes {
declarations = append(declarations, backend)
}
@@ -47,7 +47,7 @@ func (m Mesh) GetBackends(module string) []structure.BackendDeclaration {
func (m Mesh) GetModuleAddresses(moduleName string) []structure.AddressConfiguration {
addressList := make([]structure.AddressConfiguration, 0)
if nodes, ok := m.modulesMap[moduleName]; ok {
if nodes, ok := m.ModulesMap[moduleName]; ok {
for _, backend := range nodes {
addressList = append(addressList, backend.Address)
}
@@ -57,7 +57,7 @@ func (m Mesh) GetModuleAddresses(moduleName string) []structure.AddressConfigura
func (m Mesh) GetRoutes() structure.RoutingConfig {
routes := structure.RoutingConfig{}
for _, node := range m.modulesMap {
for _, node := range m.ModulesMap {
for _, backend := range node {
routes = append(routes, backend)
}
@@ -67,7 +67,7 @@ func (m Mesh) GetRoutes() structure.RoutingConfig {
func (m Mesh) CheckBackendChanged(backend structure.BackendDeclaration) (changed bool) {
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.Version != backend.Version || !oldBackend.IsPathsEqual(backend.Endpoints) || oldBackend.LibVersion != backend.LibVersion {
changed = true
@@ -83,7 +83,7 @@ func (m Mesh) CheckBackendChanged(backend structure.BackendDeclaration) (changed
func (m *Mesh) UpsertBackend(backend structure.BackendDeclaration) (changed bool) {
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.Version != backend.Version || !oldBackend.IsPathsEqual(backend.Endpoints) || oldBackend.LibVersion != backend.LibVersion {
nodes[address] = backend
@@ -94,7 +94,7 @@ func (m *Mesh) UpsertBackend(backend structure.BackendDeclaration) (changed bool
changed = true
}
} else {
m.modulesMap[backend.ModuleName] = NodesMap{address: backend}
m.ModulesMap[backend.ModuleName] = NodesMap{address: backend}
changed = true
}
return
@@ -102,18 +102,18 @@ func (m *Mesh) UpsertBackend(backend structure.BackendDeclaration) (changed bool
func (m *Mesh) DeleteBackend(backend structure.BackendDeclaration) (deleted bool) {
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 {
delete(nodes, address)
deleted = true
}
if len(nodes) == 0 {
delete(m.modulesMap, backend.ModuleName)
delete(m.ModulesMap, backend.ModuleName)
}
}
return
}
func NewMesh() *Mesh {
return &Mesh{modulesMap: make(map[string]NodesMap)}
return &Mesh{ModulesMap: make(map[string]NodesMap)}
}
+15 -15
View File
@@ -18,11 +18,11 @@ type ReadonlyModuleStore interface {
}
type ModuleStore struct {
modules []entity.Module
Modules []entity.Module
}
func (ms ModuleStore) GetByName(name string) *entity.Module {
for _, module := range ms.modules {
for _, module := range ms.Modules {
if module.Name == name {
return &module
}
@@ -31,7 +31,7 @@ func (ms ModuleStore) GetByName(name 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 {
return &module
}
@@ -40,39 +40,39 @@ func (ms ModuleStore) GetById(id string) *entity.Module {
}
func (ms *ModuleStore) UpdateByName(module entity.Module) {
for i := range ms.modules {
if ms.modules[i].Name == module.Name {
ms.modules[i] = module
for i := range ms.Modules {
if ms.Modules[i].Name == module.Name {
ms.Modules[i] = module
return
}
}
}
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 {
idsMap := StringsToMap(ids)
var deleted []entity.Module
for i := 0; i < len(ms.modules); i++ {
id := ms.modules[i].Id
for i := 0; i < len(ms.Modules); i++ {
id := ms.Modules[i].Id
if _, ok := idsMap[id]; ok {
// change modules ordering
deleted = append(deleted, ms.modules[i])
ms.modules[i] = ms.modules[len(ms.modules)-1]
ms.modules = ms.modules[:len(ms.modules)-1]
deleted = append(deleted, ms.Modules[i])
ms.Modules[i] = ms.Modules[len(ms.Modules)-1]
ms.Modules = ms.Modules[:len(ms.Modules)-1]
}
}
return deleted
}
func (ms *ModuleStore) GetAll() []entity.Module {
response := make([]entity.Module, len(ms.modules))
copy(response, ms.modules)
response := make([]entity.Module, len(ms.Modules))
copy(response, ms.Modules)
return response
}
func NewModuleStore() *ModuleStore {
return &ModuleStore{modules: make([]entity.Module, 0)}
return &ModuleStore{Modules: make([]entity.Module, 0)}
}
+10 -10
View File
@@ -15,13 +15,13 @@ type ReadonlySchemaStore interface {
}
type SchemaStore struct {
schemas []entity.ConfigSchema
Schemas []entity.ConfigSchema
}
func (ss SchemaStore) GetByModuleIds(ids []string) []entity.ConfigSchema {
idsMap := StringsToMap(ids)
result := make([]entity.ConfigSchema, 0, len(ids))
for _, schema := range ss.schemas {
for _, schema := range ss.Schemas {
if _, ok := idsMap[schema.ModuleId]; ok {
result = append(result, schema)
}
@@ -32,12 +32,12 @@ func (ss SchemaStore) GetByModuleIds(ids []string) []entity.ConfigSchema {
func (ss *SchemaStore) DeleteByIds(ids []string) int {
idsMap := StringsToMap(ids)
var deleted int
for i := 0; i < len(ss.schemas); i++ {
id := ss.schemas[i].Id
for i := 0; i < len(ss.Schemas); i++ {
id := ss.Schemas[i].Id
if _, ok := idsMap[id]; ok {
// change schemas ordering
ss.schemas[i] = ss.schemas[len(ss.schemas)-1]
ss.schemas = ss.schemas[:len(ss.schemas)-1]
ss.Schemas[i] = ss.Schemas[len(ss.Schemas)-1]
ss.Schemas = ss.Schemas[:len(ss.Schemas)-1]
deleted++
}
}
@@ -45,18 +45,18 @@ func (ss *SchemaStore) DeleteByIds(ids []string) int {
}
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 {
schema.Id = value.Id
schema.CreatedAt = value.CreatedAt
ss.schemas[key] = schema
ss.Schemas[key] = schema
return schema
}
}
ss.schemas = append(ss.schemas, schema)
ss.Schemas = append(ss.Schemas, schema)
return schema
}
func NewSchemaStore() *SchemaStore {
return &SchemaStore{schemas: make([]entity.ConfigSchema, 0)}
return &SchemaStore{Schemas: make([]entity.ConfigSchema, 0)}
}
+29 -29
View File
@@ -5,51 +5,51 @@ import (
)
type State struct {
mesh *Mesh
configs *ConfigStore
schemas *SchemaStore
modules *ModuleStore
commonConfigs *CommonConfigStore
MeshStore *Mesh
ConfigsStore *ConfigStore
SchemasStore *SchemaStore
ModulesStore *ModuleStore
CommonConfigsStore *CommonConfigStore
}
func (s State) Mesh() ReadonlyMesh {
return s.mesh
return s.MeshStore
}
func (s State) Configs() ReadonlyConfigStore {
return s.configs
return s.ConfigsStore
}
func (s State) Schemas() ReadonlySchemaStore {
return s.schemas
return s.SchemasStore
}
func (s State) Modules() ReadonlyModuleStore {
return s.modules
return s.ModulesStore
}
func (s State) CommonConfigs() ReadonlyCommonConfigStore {
return s.commonConfigs
return s.CommonConfigsStore
}
func (s *State) WritableMesh() WriteableMesh {
return s.mesh
return s.MeshStore
}
func (s *State) WritableConfigs() WriteableConfigStore {
return s.configs
return s.ConfigsStore
}
func (s *State) WritableSchemas() WriteableSchemaStore {
return s.schemas
return s.SchemasStore
}
func (s *State) WritableModules() WriteableModuleStore {
return s.modules
return s.ModulesStore
}
func (s *State) WritableCommonConfigs() WriteableCommonConfigStore {
return s.commonConfigs
return s.CommonConfigsStore
}
type WritableState interface {
@@ -69,22 +69,22 @@ type ReadonlyState interface {
CommonConfigs() ReadonlyCommonConfigStore
}
func NewState() State {
return State{
mesh: NewMesh(),
configs: NewConfigStore(),
schemas: NewSchemaStore(),
modules: NewModuleStore(),
commonConfigs: NewCommonConfigStore(),
func NewState() *State {
return &State{
MeshStore: NewMesh(),
ConfigsStore: NewConfigStore(),
SchemasStore: NewSchemaStore(),
ModulesStore: NewModuleStore(),
CommonConfigsStore: NewCommonConfigStore(),
}
}
func NewStateFromSnapshot(configs []entity.Config, schemas []entity.ConfigSchema, modules []entity.Module, commConfigs []entity.CommonConfig) State {
return State{
mesh: NewMesh(),
configs: &ConfigStore{configs: configs},
schemas: &SchemaStore{schemas: schemas},
modules: &ModuleStore{modules: modules},
commonConfigs: &CommonConfigStore{configs: commConfigs},
func NewStateFromSnapshot(configs []entity.Config, schemas []entity.ConfigSchema, modules []entity.Module, commConfigs []entity.CommonConfig) *State {
return &State{
MeshStore: NewMesh(),
ConfigsStore: &ConfigStore{Configs: configs},
SchemasStore: &SchemaStore{Schemas: schemas},
ModulesStore: &ModuleStore{Modules: modules},
CommonConfigsStore: &CommonConfigStore{Configs: commConfigs},
}
}
+4 -4
View File
@@ -63,7 +63,7 @@ func (s *Store) Apply(l *raft.Log) interface{} {
func (s *Store) Snapshot() (raft.FSMSnapshot, error) {
s.lock.Lock()
copied := deepcopy.Copy(s.state).(state.State)
copied := deepcopy.Copy(s.state).(*state.State)
s.lock.Unlock()
return &fsmSnapshot{copied}, nil
}
@@ -91,7 +91,7 @@ func (s *Store) VisitState(f func(writableState state.WritableState)) {
}
type fsmSnapshot struct {
state state.State
state *state.State
}
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 NewStateStore(st state.State) *Store {
func NewStateStore(st *state.State) *Store {
store := &Store{
state: &st,
state: st,
}
store.handlers = map[uint64]func([]byte) (interface{}, error){
cluster.UpdateBackendDeclarationCommand: store.applyUpdateBackendDeclarationCommand,
+51
View File
@@ -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
View File
@@ -15,7 +15,7 @@ import (
"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
log.Debugf(0, "handleModuleReady moduleName: %s", moduleName) // REMOVE
declaration := structure.BackendDeclaration{}
@@ -37,7 +37,7 @@ func (h *socketEventHandler) handleModuleReady(conn etp.Conn, data []byte) []byt
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)
log.Debugf(0, "handleModuleRequirements moduleName: %s", moduleName) // REMOVE
if err != nil {
@@ -59,7 +59,7 @@ func (h *socketEventHandler) handleModuleRequirements(conn etp.Conn, data []byte
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)
log.Debugf(0, "handleConfigSchema moduleName: %s", moduleName) // REMOVE
if err != nil {
@@ -95,7 +95,10 @@ func (h *socketEventHandler) handleConfigSchema(conn etp.Conn, data []byte) []by
h.store.VisitReadonlyState(func(readState state.ReadonlyState) {
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{
Id: state.GenerateId(),
Name: module.Name,
@@ -115,7 +118,3 @@ func (h *socketEventHandler) handleConfigSchema(conn etp.Conn, data []byte) []by
}
return []byte(utils.WsOkResponse)
}
func (h *socketEventHandler) handleRequestConfig(conn etp.Conn, data []byte) []byte {
panic("not implemented")
}
+1 -1
View File
@@ -8,7 +8,7 @@ import (
"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))
copy(cmdCopy, cmd)
obj, err := holder.ClusterClient.SyncApplyOnLeader(cmdCopy)
-1
View File
@@ -14,7 +14,6 @@ type connectionState struct {
func IsConfigClusterNode(conn etp.Conn) bool {
isCluster := conn.URL().Query().Get(cluster.ClusterParam)
return isCluster == "true"
}
func Parameters(conn etp.Conn) (moduleName string, err error) {
+7 -7
View File
@@ -18,12 +18,12 @@ var (
json = jsoniter.ConfigFastest
)
type socketEventHandler struct {
type SocketEventHandler struct {
server etp.Server
store *store.Store
}
func (h *socketEventHandler) SubscribeAll() {
func (h *SocketEventHandler) SubscribeAll() {
h.server.
OnConnect(h.handleConnect).
OnDisconnect(h.handleDisconnect).
@@ -34,7 +34,7 @@ func (h *socketEventHandler) SubscribeAll() {
OnWithAck(utils.ModuleSendConfigSchema, h.handleConfigSchema)
}
func (h *socketEventHandler) handleConnect(conn etp.Conn) {
func (h *SocketEventHandler) handleConnect(conn etp.Conn) {
isClusterNode := IsConfigClusterNode(conn)
moduleName, err := Parameters(conn)
log.Debugf(0, "handleConnect: %s", moduleName) // REMOVE
@@ -79,7 +79,7 @@ func (h *socketEventHandler) handleConnect(conn etp.Conn) {
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)
log.Debugf(0, "handleDisconnect: %s", moduleName) // REMOVE
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)
}
func NewSocketEventHandler(server etp.Server, store *store.Store) *socketEventHandler {
return &socketEventHandler{
func NewSocketEventHandler(server etp.Server, store *store.Store) *SocketEventHandler {
return &SocketEventHandler{
server: server,
store: store,
}