Compare commits
83
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
818ee18544 | ||
|
|
abf6a37c7a | ||
|
|
c2af71449a | ||
|
|
05eb762273 | ||
|
|
e2419e2c4b | ||
|
|
72afc94782 | ||
|
|
02070b1db1 | ||
|
|
2fc6c7ba91 | ||
|
|
c706d7932d | ||
|
|
62714cdfe1 | ||
|
|
a2c49ac39f | ||
|
|
de55ea643c | ||
|
|
5fb60e14b8 | ||
|
|
02603cb018 | ||
|
|
ffbff595d1 | ||
|
|
989429824e | ||
|
|
a31e6080e2 | ||
|
|
90e05dfb4b | ||
|
|
2af27ddb68 | ||
|
|
d004faa9e0 | ||
|
|
45a4a23112 | ||
|
|
1bb50f8175 | ||
|
|
0cbfcab3f9 | ||
|
|
d4125963b2 | ||
|
|
2e33c2275c | ||
|
|
a5b21198e0 | ||
|
|
e765cda3f9 | ||
|
|
5a91184d6c | ||
|
|
e2094296f4 | ||
|
|
777e856d00 | ||
|
|
c3f419bbc5 | ||
|
|
52705f6982 | ||
|
|
a5134181be | ||
|
|
79c801d493 | ||
|
|
f9823d5303 | ||
|
|
8339591b27 | ||
|
|
17a6e3186d | ||
|
|
213bad9722 | ||
|
|
ef33bd9fd2 | ||
|
|
123de3d452 | ||
|
|
6591bff728 | ||
|
|
88c0779aa2 | ||
|
|
95adcb117c | ||
|
|
372636f43b | ||
|
|
54dae1ab2b | ||
|
|
f0f50a8507 | ||
|
|
c3d0d5be4c | ||
|
|
929132743c | ||
|
|
6643e8937c | ||
|
|
08b4ee461e | ||
|
|
ae501969bf | ||
|
|
c29ed6d41e | ||
|
|
1c28c895b5 | ||
|
|
d9c32437c9 | ||
|
|
0429bed9e3 | ||
|
|
8bdc36a302 | ||
|
|
a3576cc3f4 | ||
|
|
713db0aa4c | ||
|
|
95aae06a41 | ||
|
|
31a4a6f5b8 | ||
|
|
1c66729974 | ||
|
|
6387947b22 | ||
|
|
3a8469c5a9 | ||
|
|
44715591ef | ||
|
|
ceb9d71a1a | ||
|
|
15ad05277b | ||
|
|
14c5b0a678 | ||
|
|
c95964fa3c | ||
|
|
a46f2cee34 | ||
|
|
1764ce9a30 | ||
|
|
384fa0417a | ||
|
|
97ba1050a7 | ||
|
|
628c506e85 | ||
|
|
9226796463 | ||
|
|
83176ba878 | ||
|
|
94cb067214 | ||
|
|
b56b6e0e42 | ||
|
|
28aa3eae33 | ||
|
|
96dee8dee3 | ||
|
|
400410c449 | ||
|
|
ab08abb3f6 | ||
|
|
01e32537a8 | ||
|
|
652d1c8c4f |
No files matched your search
@@ -0,0 +1,23 @@
|
||||
docker-build:
|
||||
image: docker:latest
|
||||
stage: build
|
||||
services:
|
||||
- docker:dind
|
||||
before_script:
|
||||
- docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
|
||||
- export VERSION=`cat .version `
|
||||
- echo $VERSION
|
||||
- echo $CI_DOCKER_FILE
|
||||
- echo $CI_REGISTRY
|
||||
script:
|
||||
- set
|
||||
- mkdir -p migrations
|
||||
- docker build -f "$CI_DOCKER_FILE" --force-rm --build-arg="version=$VERSION" --build-arg="app_name=$CI_PROJECT_NAME" --pull -t "$CI_REGISTRY/$CI_PROJECT_NAME:$VERSION" .
|
||||
- |
|
||||
docker tag "$CI_REGISTRY/$CI_PROJECT_NAME:$VERSION" "$CI_REGISTRY/$CI_PROJECT_NAME:latest"
|
||||
docker push "$CI_REGISTRY/$CI_PROJECT_NAME:$VERSION"
|
||||
docker push "$CI_REGISTRY/$CI_PROJECT_NAME:latest"
|
||||
docker rmi -f "$CI_REGISTRY/$CI_PROJECT_NAME:$VERSION"
|
||||
docker rmi -f "$CI_REGISTRY/$CI_PROJECT_NAME:latest"
|
||||
- docker logout $CI_REGISTRY
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
run:
|
||||
tests: false
|
||||
|
||||
linters:
|
||||
enable-all: true
|
||||
disable:
|
||||
- goimports
|
||||
- depguard # не используется
|
||||
- gochecknoinits
|
||||
- gochecknoglobals
|
||||
- wsl
|
||||
- gocognit
|
||||
- godox # находит тудушки, не нужно
|
||||
- golint # подумать, может вернуть
|
||||
- stylecheck # подумать, может вернуть
|
||||
|
||||
linters-settings:
|
||||
maligned:
|
||||
suggest-new: true
|
||||
lll:
|
||||
line-length: 140
|
||||
tab-width: 1
|
||||
funlen:
|
||||
lines: 80
|
||||
statements: 40
|
||||
prealloc:
|
||||
# Report preallocation suggestions only on simple loops that have no returns/breaks/continues/gotos in them.
|
||||
# True by default.
|
||||
simple: true
|
||||
range-loops: true # Report preallocation suggestions on range loops, true by default
|
||||
for-loops: true # Report preallocation suggestions on for loops, false by default
|
||||
gocritic:
|
||||
# Enable multiple checks by tags, run `GL_DEBUG=gocritic golangci-lint run` to see all tags and checks.
|
||||
# Empty list by default. See https://github.com/go-critic/go-critic#usage -> section "Tags".
|
||||
enabled-tags:
|
||||
- diagnostic
|
||||
- performance
|
||||
disabled-checks:
|
||||
- hugeParam # в данном проекте не нужен
|
||||
+49
-1
@@ -1,3 +1,51 @@
|
||||
* исправлен метод /config/get_config_by_id
|
||||
### v2.4.9
|
||||
* обновлены зависимости (исправляет panic при запуске)
|
||||
### v2.4.8
|
||||
* do not check for instance_uuid anymore
|
||||
### v2.4.7
|
||||
* updated dependencies
|
||||
### v2.4.6
|
||||
* increase default version config count to 15
|
||||
* fix leader address race on leader disconnect (it was possible that after the change of the leader, one of the nodes will not be declared available, although this is not so)
|
||||
* enable metric server
|
||||
* add integration test for multiple config updates
|
||||
* fix service hanging on shutdown
|
||||
* improve raft logging
|
||||
* fix deadlock in cluster client
|
||||
* add timeouts to all websocket emits to prevent connections leakage
|
||||
### v2.4.5
|
||||
* updated isp-lib
|
||||
### v2.4.4
|
||||
* fix marshaling body of `ERROR_CONNECTION` event
|
||||
### v2.4.3
|
||||
* updated isp-lib
|
||||
* updated isp-event-lib
|
||||
### v2.4.2
|
||||
* add db pass part
|
||||
### v2.4.1
|
||||
* updated method `/config/get_configs_by_module_id`
|
||||
### v2.4.0
|
||||
* add method `/config/get_config_by_id`
|
||||
* add method `/config/get_configs_by_module_id`
|
||||
* updated docs
|
||||
### v2.3.1
|
||||
* fix old configs order
|
||||
* add `createdAt` field to config version
|
||||
### v2.3.0
|
||||
* add method `/module/broadcast_event` to broadcast arbitrary event to modules
|
||||
* add module dependencies to response `/module/get_modules_info`
|
||||
* add option to create a new config version instead update it
|
||||
* fix broadcasting config on activating and upserting configs
|
||||
* add saving old configs
|
||||
* add method `/config/delete_version`
|
||||
* add method `/config/get_all_version`
|
||||
* update libs
|
||||
|
||||
### v2.2.1
|
||||
* update deps
|
||||
* fix bug in json schema marshaling/unmarshaling
|
||||
|
||||
### v2.2.0
|
||||
* migrate to go modules
|
||||
* add linter, refactor
|
||||
@@ -12,7 +60,7 @@
|
||||
* 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
|
||||
* fix panic type casting in snapshot
|
||||
* create empty default config now
|
||||
* add method `/module/get_by_name` to fetch module object by name
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
FROM dockerhub.mos.ru/mosos/arbat:15.5 as builder
|
||||
RUN zypper --no-gpg-checks update -y && zypper --no-gpg-checks install -y go1.23 git
|
||||
WORKDIR /build
|
||||
ARG version
|
||||
ENV version_env=$version
|
||||
ARG app_name
|
||||
ENV app_name_env=$app_name
|
||||
COPY . .
|
||||
ENV GOPROXY=https://repo-mirror.mos.ru/repository/go-public
|
||||
RUN go build -ldflags="-X 'main.version=$version_env'" -o /main .
|
||||
|
||||
FROM dockerhub.mos.ru/mosos/arbat:15.5
|
||||
|
||||
RUN cp /usr/share/zoneinfo/Europe/Moscow /etc/localtime
|
||||
RUN echo "Europe/Moscow" > /etc/timezone
|
||||
|
||||
ARG UID=10001
|
||||
RUN useradd \
|
||||
--home "/nonexistent" \
|
||||
--shell "/sbin/nologin" \
|
||||
--no-create-home \
|
||||
--uid "${UID}" \
|
||||
--user-group \
|
||||
appuser
|
||||
|
||||
RUN mkdir -p /app/data
|
||||
RUN chown appuser:appuser /app/data
|
||||
VOLUME /app/data
|
||||
|
||||
USER appuser
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
ARG app_name
|
||||
ENV app_name_env=$app_name
|
||||
COPY --from=builder main /app/$app_name_env
|
||||
COPY /conf/config.yml /app/config.yml
|
||||
COPY /conf/default_remote_config.json* /app/default_remote_config.json
|
||||
COPY /migrations /app/migrations
|
||||
|
||||
ENTRYPOINT /app/$app_name_env
|
||||
+36
-29
@@ -2,9 +2,11 @@ package cluster
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/integration-system/isp-lib/v2/atomic"
|
||||
"github.com/integration-system/isp-lib/v2/structure"
|
||||
"github.com/integration-system/isp-lib/v2/utils"
|
||||
log "github.com/integration-system/isp-log"
|
||||
@@ -31,6 +33,7 @@ type Client struct {
|
||||
r *raft.Raft
|
||||
|
||||
leaderMu sync.RWMutex
|
||||
isLeader *atomic.AtomicBool
|
||||
leaderState leaderState
|
||||
leaderClient *SocketLeaderClient
|
||||
declaration structure.BackendDeclaration
|
||||
@@ -50,10 +53,7 @@ func (client *Client) Shutdown() error {
|
||||
}
|
||||
|
||||
func (client *Client) IsLeader() bool {
|
||||
client.leaderMu.RLock()
|
||||
defer client.leaderMu.RUnlock()
|
||||
|
||||
return client.leaderState.isLeader
|
||||
return client.isLeader.Get()
|
||||
}
|
||||
|
||||
func (client *Client) SyncApply(command []byte) (*ApplyLogResponse, error) {
|
||||
@@ -67,25 +67,27 @@ func (client *Client) SyncApply(command []byte) (*ApplyLogResponse, error) {
|
||||
if client.leaderState.isLeader {
|
||||
apply, err := client.r.SyncApply(command)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, fmt.Errorf("apply to raft as a leader: %v", err)
|
||||
}
|
||||
logResponse := apply.(ApplyLogResponse)
|
||||
return &logResponse, err
|
||||
} else {
|
||||
if client.leaderClient == nil {
|
||||
return nil, ErrLeaderClientNotInitialized
|
||||
}
|
||||
response, err := client.leaderClient.Ack(command, defaultApplyTimeout)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var logResponse ApplyLogResponse
|
||||
err = json.Unmarshal(response, &logResponse)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &logResponse, nil
|
||||
}
|
||||
|
||||
if client.leaderClient == nil {
|
||||
return nil, ErrLeaderClientNotInitialized
|
||||
}
|
||||
response, err := client.leaderClient.Ack(command, defaultApplyTimeout)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("send to leader to apply: %v", err)
|
||||
}
|
||||
|
||||
var logResponse ApplyLogResponse
|
||||
err = json.Unmarshal(response, &logResponse)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &logResponse, nil
|
||||
}
|
||||
|
||||
func (client *Client) SyncApplyOnLeader(command []byte) (*ApplyLogResponse, error) {
|
||||
@@ -97,10 +99,10 @@ func (client *Client) SyncApplyOnLeader(command []byte) (*ApplyLogResponse, erro
|
||||
}
|
||||
apply, err := client.r.SyncApply(command)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, fmt.Errorf("apply to raft as a leader: %v", err)
|
||||
}
|
||||
logResponse := apply.(ApplyLogResponse)
|
||||
return &logResponse, err
|
||||
return &logResponse, nil
|
||||
}
|
||||
|
||||
func (client *Client) listenLeader() {
|
||||
@@ -113,17 +115,16 @@ func (client *Client) listenLeader() {
|
||||
}).Info(codes.LeaderStateChanged, "leader state changed")
|
||||
|
||||
if client.leaderClient != nil {
|
||||
log.Debugf(0, "close previous leader ws connection %s", client.leaderState.leaderAddr)
|
||||
client.leaderClient.Close()
|
||||
client.leaderClient = nil
|
||||
}
|
||||
if n.LeaderElected && !n.IsLeader {
|
||||
leaderClient := NewSocketLeaderClient(n.CurrentLeaderAddress, func() {
|
||||
client.onClientDisconnect(client.leaderState.leaderAddr)
|
||||
leaderAddr := n.CurrentLeaderAddress
|
||||
leaderClient := NewSocketLeaderClient(leaderAddr, func() {
|
||||
client.onClientDisconnect(leaderAddr)
|
||||
})
|
||||
if err := leaderClient.Dial(leaderConnectionTimeout); err != nil {
|
||||
log.Fatalf(codes.LeaderClientConnectionError, "could not connect to leader: %v", err)
|
||||
continue
|
||||
}
|
||||
client.leaderClient = leaderClient
|
||||
|
||||
@@ -137,6 +138,7 @@ func (client *Client) listenLeader() {
|
||||
isLeader: n.IsLeader,
|
||||
leaderAddr: n.CurrentLeaderAddress,
|
||||
}
|
||||
client.isLeader.Set(n.IsLeader)
|
||||
|
||||
client.leaderMu.Unlock()
|
||||
}
|
||||
@@ -146,7 +148,9 @@ func (client *Client) declareMyselfToLeader(leaderClient *SocketLeaderClient) {
|
||||
if err != nil {
|
||||
log.Warnf(codes.SendDeclarationToLeader, "send declaration to leader. err: %v", err)
|
||||
} else if response != utils.WsOkResponse {
|
||||
log.Warnf(codes.SendDeclarationToLeader, "send declaration to leader. response: %s", response)
|
||||
log.Warnf(codes.SendDeclarationToLeader, "send declaration to leader. error response: '%s'", response)
|
||||
} else {
|
||||
log.Info(codes.SendDeclarationToLeader, "successfully sent my declaration to leader")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,10 +164,10 @@ func (client *Client) declareMyselfToCluster() {
|
||||
LastConnectedAt: now,
|
||||
}
|
||||
command := PrepareModuleConnectedCommand(module)
|
||||
syncApplyCommand(client, command, "ModuleConnectedCommand")
|
||||
syncApplyCommand(client, command)
|
||||
|
||||
declarationCommand := PrepareUpdateBackendDeclarationCommand(client.declaration)
|
||||
syncApplyCommand(client, declarationCommand, "UpdateBackendDeclarationCommand")
|
||||
syncApplyCommand(client, declarationCommand)
|
||||
}
|
||||
|
||||
type leaderState struct {
|
||||
@@ -178,21 +182,24 @@ func NewRaftClusterClient(r *raft.Raft, declaration structure.BackendDeclaration
|
||||
declaration: declaration,
|
||||
leaderState: leaderState{},
|
||||
onClientDisconnect: onLeaderDisconnect,
|
||||
isLeader: atomic.NewAtomicBool(false),
|
||||
}
|
||||
go client.listenLeader()
|
||||
|
||||
return client
|
||||
}
|
||||
|
||||
func syncApplyCommand(clusterClient *Client, command []byte, commandName string) {
|
||||
func syncApplyCommand(clusterClient *Client, command []byte) {
|
||||
applyLogResponse, err := clusterClient.SyncApply(command)
|
||||
if err != nil {
|
||||
commandName := ParseCommand(command).String()
|
||||
log.WithMetadata(map[string]interface{}{
|
||||
"command": string(command),
|
||||
"commandName": commandName,
|
||||
}).Warnf(codes.SyncApplyError, "announce myself. apply command: %v", err)
|
||||
}
|
||||
if applyLogResponse != nil && applyLogResponse.ApplyError != "" {
|
||||
commandName := ParseCommand(command).String()
|
||||
log.WithMetadata(map[string]interface{}{
|
||||
"result": string(applyLogResponse.Result),
|
||||
"applyError": applyLogResponse.ApplyError,
|
||||
|
||||
+25
-4
@@ -15,10 +15,16 @@ const (
|
||||
ApplyCommandEvent = "CONFIG_CLUSTER:APPLY_COMMAND"
|
||||
CommandSizeBytes = 8
|
||||
|
||||
ClusterParam = "cluster"
|
||||
GETParam = "cluster"
|
||||
)
|
||||
|
||||
type Command uint64
|
||||
|
||||
// needed: go get golang.org/x/tools/cmd/stringer
|
||||
//go:generate stringer -type=Command -output const_string.go
|
||||
|
||||
const (
|
||||
_ = iota
|
||||
_ Command = iota
|
||||
UpdateBackendDeclarationCommand
|
||||
DeleteBackendDeclarationCommand
|
||||
|
||||
@@ -27,6 +33,7 @@ const (
|
||||
ModuleConnectedCommand
|
||||
ModuleDisconnectedCommand
|
||||
DeleteModulesCommand
|
||||
DeleteVersionConfigCommand
|
||||
|
||||
ActivateConfigCommand
|
||||
DeleteConfigsCommand
|
||||
@@ -34,8 +41,14 @@ const (
|
||||
|
||||
DeleteCommonConfigsCommand
|
||||
UpsertCommonConfigCommand
|
||||
|
||||
BroadcastEventCommand
|
||||
)
|
||||
|
||||
func ParseCommand(data []byte) Command {
|
||||
return Command(binary.BigEndian.Uint64(data[:CommandSizeBytes]))
|
||||
}
|
||||
|
||||
func PrepareUpdateBackendDeclarationCommand(backend structure.BackendDeclaration) []byte {
|
||||
return prepareCommand(UpdateBackendDeclarationCommand, backend)
|
||||
}
|
||||
@@ -80,9 +93,17 @@ func PrepareUpsertCommonConfigCommand(config UpsertCommonConfig) []byte {
|
||||
return prepareCommand(UpsertCommonConfigCommand, config)
|
||||
}
|
||||
|
||||
func prepareCommand(command uint64, payload interface{}) []byte {
|
||||
func PrepareBroadcastEventCommand(event BroadcastEvent) []byte {
|
||||
return prepareCommand(BroadcastEventCommand, event)
|
||||
}
|
||||
|
||||
func PrepareDeleteConfigVersionCommand(id string) []byte {
|
||||
return prepareCommand(DeleteVersionConfigCommand, Identity{Id: id})
|
||||
}
|
||||
|
||||
func prepareCommand(command Command, payload interface{}) []byte {
|
||||
cmd := make([]byte, 8)
|
||||
binary.BigEndian.PutUint64(cmd, command)
|
||||
binary.BigEndian.PutUint64(cmd, uint64(command))
|
||||
buf := bytes.NewBuffer(cmd)
|
||||
err := json.NewEncoder(buf).Encode(payload)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
// Code generated by "stringer -type=Command -output const_string.go"; DO NOT EDIT.
|
||||
|
||||
package cluster
|
||||
|
||||
import "strconv"
|
||||
|
||||
func _() {
|
||||
// An "invalid array index" compiler error signifies that the constant values have changed.
|
||||
// Re-run the stringer command to generate them again.
|
||||
var x [1]struct{}
|
||||
_ = x[UpdateBackendDeclarationCommand-1]
|
||||
_ = x[DeleteBackendDeclarationCommand-2]
|
||||
_ = x[UpdateConfigSchemaCommand-3]
|
||||
_ = x[ModuleConnectedCommand-4]
|
||||
_ = x[ModuleDisconnectedCommand-5]
|
||||
_ = x[DeleteModulesCommand-6]
|
||||
_ = x[DeleteVersionConfigCommand-7]
|
||||
_ = x[ActivateConfigCommand-8]
|
||||
_ = x[DeleteConfigsCommand-9]
|
||||
_ = x[UpsertConfigCommand-10]
|
||||
_ = x[DeleteCommonConfigsCommand-11]
|
||||
_ = x[UpsertCommonConfigCommand-12]
|
||||
_ = x[BroadcastEventCommand-13]
|
||||
}
|
||||
|
||||
const _Command_name = "UpdateBackendDeclarationCommandDeleteBackendDeclarationCommandUpdateConfigSchemaCommandModuleConnectedCommandModuleDisconnectedCommandDeleteModulesCommandDeleteVersionConfigCommandActivateConfigCommandDeleteConfigsCommandUpsertConfigCommandDeleteCommonConfigsCommandUpsertCommonConfigCommandBroadcastEventCommand"
|
||||
|
||||
var _Command_index = [...]uint16{0, 31, 62, 87, 109, 134, 154, 180, 201, 221, 240, 266, 291, 312}
|
||||
|
||||
func (i Command) String() string {
|
||||
i -= 1
|
||||
if i >= Command(len(_Command_index)-1) {
|
||||
return "Command(" + strconv.FormatInt(int64(i+1), 10) + ")"
|
||||
}
|
||||
return _Command_name[_Command_index[i]:_Command_index[i+1]]
|
||||
}
|
||||
+18
-4
@@ -3,9 +3,10 @@ package cluster
|
||||
import (
|
||||
json2 "encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
"isp-config-service/entity"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ApplyLogResponse struct {
|
||||
@@ -27,9 +28,11 @@ type ActivateConfig struct {
|
||||
}
|
||||
|
||||
type UpsertConfig struct {
|
||||
Config entity.Config
|
||||
Create bool
|
||||
Unsafe bool
|
||||
Config entity.Config
|
||||
VersionId string
|
||||
VersionCreateAt time.Time
|
||||
Create bool
|
||||
Unsafe bool
|
||||
}
|
||||
|
||||
type DeleteConfigs struct {
|
||||
@@ -40,11 +43,22 @@ type DeleteCommonConfig struct {
|
||||
Id string
|
||||
}
|
||||
|
||||
type Identity struct {
|
||||
Id string
|
||||
}
|
||||
|
||||
type UpsertCommonConfig struct {
|
||||
Config entity.CommonConfig
|
||||
Create bool
|
||||
}
|
||||
|
||||
type BroadcastEvent struct {
|
||||
Event string
|
||||
ModuleNames []string
|
||||
PerformUntil time.Time // stateless events, must be broadcast until this in UTC
|
||||
Payload json2.RawMessage
|
||||
}
|
||||
|
||||
type ResponseWithError struct {
|
||||
Response interface{}
|
||||
Error string
|
||||
|
||||
@@ -62,15 +62,17 @@ func (c *SocketLeaderClient) Close() {
|
||||
c.cancel()
|
||||
err := c.client.Close()
|
||||
if err != nil {
|
||||
log.Warnf(codes.LeaderClientConnectionError, "leader client close err: %v", err)
|
||||
log.Warnf(codes.LeaderClientConnectionError, "leader client %s close err: %v", c.url, err)
|
||||
}
|
||||
log.Debug(0, "leader client connection closed")
|
||||
log.Debugf(0, "close previous leader ws connection %s", c.url)
|
||||
}
|
||||
|
||||
func NewSocketLeaderClient(address string, leaderDisconnectionCallback func()) *SocketLeaderClient {
|
||||
etpConfig := etp.Config{
|
||||
HttpClient: http.DefaultClient,
|
||||
ConnectionReadLimit: WsConnectionReadLimit,
|
||||
HttpClient: &http.Client{},
|
||||
ConnectionReadLimit: WsConnectionReadLimit,
|
||||
WorkersNum: 1,
|
||||
WorkersBufferMultiplier: 1,
|
||||
}
|
||||
client := etp.NewClient(etpConfig)
|
||||
leaderClient := &SocketLeaderClient{
|
||||
@@ -84,12 +86,16 @@ func NewSocketLeaderClient(address string, leaderDisconnectionCallback func()) *
|
||||
leaderClient.client.OnDisconnect(func(err error) {
|
||||
log.WithMetadata(map[string]interface{}{
|
||||
"leaderAddr": address,
|
||||
"error": err,
|
||||
}).Warn(codes.LeaderClientDisconnected, "disconnected ws from leader")
|
||||
leaderDisconnectionCallback()
|
||||
})
|
||||
|
||||
leaderClient.client.OnError(func(err error) {
|
||||
log.Warnf(codes.LeaderClientConnectionError, "leader client on error: %v", err)
|
||||
log.WithMetadata(map[string]interface{}{
|
||||
"leaderAddr": address,
|
||||
"error": err,
|
||||
}).Warn(codes.LeaderClientDisconnected, "leader client on error")
|
||||
})
|
||||
leaderClient.client.OnConnect(func() {
|
||||
log.WithMetadata(map[string]interface{}{
|
||||
@@ -107,9 +113,7 @@ func getURL(address string) string {
|
||||
cfg := config.Get().(*conf.Configuration)
|
||||
|
||||
params := url.Values{}
|
||||
params.Add(ClusterParam, "true")
|
||||
// TODO выпилить instance_uuid ?
|
||||
params.Add(GETParam, "true")
|
||||
params.Add(utils.ModuleNameGetParamKey, cfg.ModuleName)
|
||||
params.Add(utils.InstanceUuidGetParamKey, "9d89354b-c728-4b48-b002-a7d3b229f151")
|
||||
return fmt.Sprintf("ws://%s:%d/isp-etp/?%s", addr.IP.String(), addr.Port, params.Encode())
|
||||
}
|
||||
@@ -37,3 +37,5 @@ cluster:
|
||||
bootstrapCluster: true
|
||||
peers:
|
||||
- 127.0.0.1:9001
|
||||
|
||||
versionConfigCount: 15
|
||||
@@ -1,10 +1,7 @@
|
||||
moduleName: config
|
||||
instanceUuid: bf482806-0c3d-4e0d-b9d4-12c037b12d70
|
||||
|
||||
registry:
|
||||
host: nexus.msp.mobi
|
||||
username: mp3deployer
|
||||
password: ScjKLQuvqfAXu2bs8ysLAvRt
|
||||
|
||||
images:
|
||||
module: nexus.msp.mobi/msp2/dev/isp-config-service:latest
|
||||
@@ -1,4 +1,4 @@
|
||||
//nolint lll
|
||||
//nolint:lll
|
||||
package conf
|
||||
|
||||
import (
|
||||
@@ -6,12 +6,13 @@ import (
|
||||
)
|
||||
|
||||
type Configuration struct {
|
||||
Database structure.DBConfiguration `valid:"required~Required" schema:"База данных,настройка параметров подключения к базе данных"`
|
||||
GrpcOuterAddress structure.AddressConfiguration `valid:"required~Required" json:"grpcOuterAddress"`
|
||||
ModuleName string `valid:"required~Required"`
|
||||
WS WebService `valid:"required~Required" schema:"Конфигурация веб сервиса"`
|
||||
Metrics structure.MetricConfiguration
|
||||
Cluster ClusterConfiguration `valid:"required~Required"`
|
||||
Database structure.DBConfiguration `valid:"required~Required" schema:"База данных,настройка параметров подключения к базе данных"`
|
||||
GrpcOuterAddress structure.AddressConfiguration `valid:"required~Required" json:"grpcOuterAddress"`
|
||||
ModuleName string `valid:"required~Required"`
|
||||
WS WebService `valid:"required~Required" schema:"Конфигурация веб сервиса"`
|
||||
Metrics structure.MetricConfiguration
|
||||
Cluster ClusterConfiguration `valid:"required~Required"`
|
||||
VersionConfigCount int `schema:"Количество сохраняемых старых версий конфигурации"`
|
||||
}
|
||||
|
||||
type ClusterConfiguration struct {
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
{}
|
||||
@@ -1,336 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/integration-system/isp-lib-test/ctx"
|
||||
"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/v2/backend"
|
||||
"github.com/integration-system/isp-lib/v2/structure"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"google.golang.org/grpc"
|
||||
"isp-config-service/conf"
|
||||
"isp-config-service/domain"
|
||||
)
|
||||
|
||||
const (
|
||||
configServiceHttpPort = "9001"
|
||||
configServiceGrpcPort = "9002"
|
||||
configServiceSchema = "config_service"
|
||||
|
||||
configsNumber = 3
|
||||
maxAwaitingTime = 25 * time.Second
|
||||
attemptTimeout = 300 * time.Millisecond
|
||||
|
||||
deleteCommonConfigsCommand = "config/common_config/delete_config"
|
||||
getRoutesCommand = "config/routing/get_routes"
|
||||
)
|
||||
|
||||
var (
|
||||
pgCfg structure.DBConfiguration
|
||||
|
||||
configsHttpAddrs = make([]structure.AddressConfiguration, configsNumber)
|
||||
configsGrpcAddrs = make([]structure.AddressConfiguration, configsNumber)
|
||||
configsCtxs = make([]*docker.ContainerContext, configsNumber)
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
cfg := ctx.BaseTestConfiguration{}
|
||||
test, err := ctx.NewIntegrationTest(m, &cfg, setup)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
test.PrepareAndRun()
|
||||
}
|
||||
|
||||
func setup(testCtx *ctx.TestContext, runTest func() int) int {
|
||||
cfg := testCtx.BaseConfiguration()
|
||||
|
||||
cli, err := docker.NewClient()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
defer cli.Close()
|
||||
env := docker.NewTestEnvironment(testCtx, cli)
|
||||
defer env.Cleanup()
|
||||
|
||||
_, pgCfg = env.RunPGContainer()
|
||||
_, err = postgres.Wait(pgCfg, 10*time.Second)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
pgCfg.Schema = configServiceSchema
|
||||
|
||||
configs := make([]conf.Configuration, configsNumber)
|
||||
peersAddrs := make([]string, configsNumber)
|
||||
|
||||
for i := 0; i < configsNumber; i++ {
|
||||
httpAddr := getConfigServiceAddress(i, configServiceHttpPort)
|
||||
grpcAddr := getConfigServiceAddress(i, configServiceGrpcPort)
|
||||
cfg := conf.Configuration{
|
||||
Database: pgCfg,
|
||||
ModuleName: moduleName,
|
||||
GrpcOuterAddress: grpcAddr,
|
||||
WS: conf.WebService{
|
||||
Rest: httpAddr,
|
||||
Grpc: grpcAddr,
|
||||
},
|
||||
Cluster: conf.ClusterConfiguration{
|
||||
InMemory: false,
|
||||
DataDir: "./data",
|
||||
Peers: nil,
|
||||
OuterAddress: httpAddr.GetAddress(),
|
||||
ConnectTimeoutSeconds: 10,
|
||||
BootstrapCluster: false,
|
||||
},
|
||||
}
|
||||
configsGrpcAddrs[i] = grpcAddr
|
||||
configsHttpAddrs[i] = httpAddr
|
||||
configs[i] = cfg
|
||||
peersAddrs[i] = httpAddr.GetAddress()
|
||||
}
|
||||
|
||||
configs[0].Cluster.BootstrapCluster = true
|
||||
|
||||
for i := 0; i < configsNumber; i++ {
|
||||
c := configs[i]
|
||||
peersAddrsEnv := generatePeersConfigEnv(peersAddrs)
|
||||
peersAddrsEnv["LOG_LEVEL"] = "debug"
|
||||
ctx := env.RunAppContainer(
|
||||
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),
|
||||
)
|
||||
grpcAddr := configsGrpcAddrs[i]
|
||||
grpcAddr.IP = ctx.GetIPAddress()
|
||||
configsGrpcAddrs[i] = grpcAddr
|
||||
|
||||
httpAddr := configsHttpAddrs[i]
|
||||
httpAddr.IP = ctx.GetIPAddress()
|
||||
configsHttpAddrs[i] = httpAddr
|
||||
|
||||
configsCtxs[i] = ctx
|
||||
}
|
||||
|
||||
//time.Sleep(3 * time.Second)
|
||||
return runTest()
|
||||
}
|
||||
|
||||
func TestClusterElection(t *testing.T) {
|
||||
defer func() {
|
||||
err := recover()
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
}
|
||||
}()
|
||||
a := assert.New(t)
|
||||
var ready bool
|
||||
|
||||
ready = testClusterReady(a, -1)
|
||||
if !ready {
|
||||
return
|
||||
}
|
||||
|
||||
for i := 0; i < configsNumber; i++ {
|
||||
fmt.Print("\n\n\n")
|
||||
log.Printf("stopping %d container\n", i)
|
||||
a.NoError(configsCtxs[i].StopContainer(20 * time.Second))
|
||||
|
||||
time.Sleep(5 * time.Second)
|
||||
fmt.Print("\n\n\n")
|
||||
log.Printf("checking cluster except %d\n", i)
|
||||
ready = testClusterReady(a, i)
|
||||
if !ready {
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Print("\n\n\n")
|
||||
log.Printf("starting %d container\n", i)
|
||||
a.NoError(configsCtxs[i].StartContainer())
|
||||
|
||||
time.Sleep(3 * time.Second)
|
||||
log.Printf("checking cluster, iteration %d\n", i+1)
|
||||
ready = testClusterReady(a, -1)
|
||||
if !ready {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func getConfigServiceAddress(num int, port string) structure.AddressConfiguration {
|
||||
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),
|
||||
IP: ip.String(),
|
||||
Port: port,
|
||||
}
|
||||
}
|
||||
|
||||
func testClusterReady(a *assert.Assertions, except int) bool {
|
||||
var clients []*backend.InternalGrpcClient
|
||||
defer func() {
|
||||
for _, client := range clients {
|
||||
client.CloseQuietly()
|
||||
}
|
||||
}()
|
||||
|
||||
for j := 0; j < configsNumber; j++ {
|
||||
if j == except {
|
||||
continue
|
||||
}
|
||||
configAddr := configsGrpcAddrs[j]
|
||||
client := testGrpcReady(configAddr, a)
|
||||
if client == nil {
|
||||
a.Fail(fmt.Sprintf("unable to connect to %d config", j))
|
||||
return false
|
||||
}
|
||||
clients = append(clients, client)
|
||||
ready := testRaftReady(client, a)
|
||||
if !ready {
|
||||
return ready
|
||||
}
|
||||
}
|
||||
|
||||
prevRoutes := getRoutes(clients[0], a)
|
||||
routesLen := len(clients)
|
||||
for i := 1; i < len(clients); i++ {
|
||||
routes := getRoutes(clients[i], a)
|
||||
t := a.Len(routes, routesLen, "invalid length")
|
||||
if !t {
|
||||
return t
|
||||
}
|
||||
match := a.ElementsMatch(prevRoutes, routes, "different backend declarations")
|
||||
if !match {
|
||||
return match
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func testGrpcReady(configAddr structure.AddressConfiguration, a *assert.Assertions) *backend.InternalGrpcClient {
|
||||
start := time.Now()
|
||||
var client *backend.InternalGrpcClient
|
||||
var err error
|
||||
_, _ = await(func() (interface{}, error) {
|
||||
client, err = backend.NewGrpcClient(
|
||||
configAddr.GetAddress(),
|
||||
grpc.WithBlock(),
|
||||
grpc.WithInsecure(),
|
||||
)
|
||||
//log.Println("connect to grpc err:", err)
|
||||
return nil, err
|
||||
}, maxAwaitingTime, attemptTimeout)
|
||||
if !a.NoError(err) {
|
||||
return nil
|
||||
}
|
||||
log.Println("waiting until grpc ready:", time.Since(start).Round(time.Second))
|
||||
return client
|
||||
}
|
||||
|
||||
func testRaftReady(client *backend.InternalGrpcClient, a *assert.Assertions) bool {
|
||||
var err error
|
||||
req := new(domain.ConfigIdRequest)
|
||||
req.Id = "33"
|
||||
response := new(structure.GrpcError)
|
||||
start := time.Now()
|
||||
f := func() (interface{}, error) {
|
||||
err = client.Invoke(
|
||||
deleteCommonConfigsCommand,
|
||||
-1,
|
||||
req,
|
||||
response,
|
||||
)
|
||||
//log.Println("send grpc request. response: ", response, "err: ", err)
|
||||
return nil, err
|
||||
}
|
||||
_, _ = 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
|
||||
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, attemptTimeout time.Duration) (interface{}, error) {
|
||||
retryer := utils.NewRetryer(dialer, timeout)
|
||||
retryer.AttemptTimeout = attemptTimeout
|
||||
return retryer.Do()
|
||||
}
|
||||
|
||||
func generatePeersConfigEnv(peers []string) map[string]string {
|
||||
key := "LC_ISP_CLUSTER.PEERS"
|
||||
val := strings.Join(peers, ",")
|
||||
return map[string]string{
|
||||
key: val,
|
||||
}
|
||||
}
|
||||
|
||||
type writeLogger struct {
|
||||
prefix string
|
||||
w io.Writer
|
||||
filter string
|
||||
}
|
||||
|
||||
func (l *writeLogger) Write(p []byte) (int, error) {
|
||||
lines := bytes.SplitAfter(p, []byte("\n"))
|
||||
for _, line := range lines {
|
||||
s := string(line)
|
||||
if l.filter != "" && strings.Contains(s, l.filter) || strings.TrimSpace(s) == "" {
|
||||
continue
|
||||
}
|
||||
_, err := l.w.Write(p)
|
||||
if err != nil {
|
||||
fmt.Printf("%s %s: %v", l.prefix, s, err)
|
||||
} else {
|
||||
fmt.Printf("%s %s", l.prefix, s)
|
||||
}
|
||||
}
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
// NewWriteLogger returns a writer that behaves like w except
|
||||
// that it logs (using fmt.Printf) each write to standard error,
|
||||
// printing the prefix and the string data written.
|
||||
func NewWriteLogger(prefix string, w io.Writer, filter string) io.Writer {
|
||||
return &writeLogger{prefix, w, filter}
|
||||
}
|
||||
+14
-19
@@ -15,12 +15,11 @@ type commonConfig struct {
|
||||
rstore *store.Store
|
||||
}
|
||||
|
||||
// GetConfigs godoc
|
||||
// @Summary Метод получения объектов конфигурации по идентификаторам
|
||||
// @Description Возвращает массив конфигураций по запрошенным идентификаторам (все, если массив пустой)
|
||||
// @Tags Общие конфигурации
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {array} entity.CommonConfig
|
||||
// @Router /common_config/get_configs [POST]
|
||||
func (c *commonConfig) GetConfigs(identities []string) []entity.CommonConfig {
|
||||
@@ -35,13 +34,12 @@ func (c *commonConfig) GetConfigs(identities []string) []entity.CommonConfig {
|
||||
return response
|
||||
}
|
||||
|
||||
// CreateUpdateConfig godoc
|
||||
// @Summary Метод обновления общей конфигурации
|
||||
// @Description Если конфиг с таким id существует, то обновляет данные, если нет, то добавляет данные в базу
|
||||
// В случае обновления рассылает все подключенным модулям актуальную конфигурацию
|
||||
// @Description В случае обновления рассылает всем подключенным модулям актуальную конфигурацию
|
||||
// @Tags Общие конфигурации
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body entity.CommonConfig true "объект для сохранения"
|
||||
// @Success 200 {object} entity.CommonConfig
|
||||
// @Failure 404 {object} structure.GrpcError "если конфигурация не найдена"
|
||||
@@ -60,19 +58,18 @@ func (c *commonConfig) CreateUpdateConfig(config entity.CommonConfig) (*entity.C
|
||||
upsertConfig.Create = true
|
||||
}
|
||||
command := cluster.PrepareUpsertCommonConfigCommand(upsertConfig)
|
||||
err := PerformSyncApplyWithError(command, "UpsertCommonConfigCommand", &response)
|
||||
err := PerformSyncApplyWithError(command, &response)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &response, nil
|
||||
}
|
||||
|
||||
// DeleteConfigs godoc
|
||||
// @Summary Метод удаления объектов общей конфигурации по идентификаторам
|
||||
// @Description Возвращает флаг удаления и набор связей с модулями и конфигурациями, в случае наличия связей deleted всегда false
|
||||
// @Tags Общие конфигурации
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.ConfigIdRequest true "id общей конфигурации"
|
||||
// @Success 200 {object} domain.DeleteCommonConfigResponse
|
||||
// @Failure 500 {object} structure.GrpcError
|
||||
@@ -80,19 +77,18 @@ func (c *commonConfig) CreateUpdateConfig(config entity.CommonConfig) (*entity.C
|
||||
func (c *commonConfig) DeleteConfigs(req domain.ConfigIdRequest) (*domain.DeleteCommonConfigResponse, error) {
|
||||
var response domain.DeleteCommonConfigResponse
|
||||
command := cluster.PrepareDeleteCommonConfigsCommand(req.Id)
|
||||
err := PerformSyncApplyWithError(command, "DeleteCommonConfigsCommand", &response)
|
||||
err := PerformSyncApplyWithError(command, &response)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &response, nil
|
||||
}
|
||||
|
||||
// CompileConfigs godoc
|
||||
// @Summary Метод компиляции итоговой конфигурации для модулей
|
||||
// @Description Возвращает скомпилированный объект конфигурации
|
||||
// @Tags Общие конфигурации
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.CompileConfigsRequest true "перечисление идентификаторов общей конфигурации и исхдных конфиг"
|
||||
// @Success 200 {object} domain.CompiledConfigResponse
|
||||
// @Router /common_config/compile [POST]
|
||||
@@ -104,19 +100,18 @@ func (c *commonConfig) CompileConfigs(req domain.CompileConfigsRequest) domain.C
|
||||
return result
|
||||
}
|
||||
|
||||
// GetLinks godoc
|
||||
// @Summary Метод получения связей общей конфигурациями с конфигурацией модулей
|
||||
// @Description Возвращает ассоциативный массив, ключами которого являются название модулей, а значения - название конфигурации модуля
|
||||
// @Tags Общие конфигурации
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.ConfigIdRequest true "id общей конфигурации"
|
||||
// @Success 200 {object} domain.CommonConfigLinks
|
||||
// @Router /common_config/get_links [POST]
|
||||
func (c *commonConfig) GetLinks(req domain.ConfigIdRequest) domain.CommonConfigLinks {
|
||||
var result domain.CommonConfigLinks
|
||||
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
|
||||
result = service.CommonConfigService.GetCommonConfigLinks(req.Id, state)
|
||||
result = service.CommonConfig.GetCommonConfigLinks(req.Id, state)
|
||||
})
|
||||
return result
|
||||
}
|
||||
|
||||
+115
-18
@@ -1,12 +1,15 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/integration-system/isp-lib/v2/utils"
|
||||
"google.golang.org/grpc/codes"
|
||||
"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"
|
||||
)
|
||||
@@ -17,12 +20,11 @@ type config struct {
|
||||
rstore *store.Store
|
||||
}
|
||||
|
||||
// GetActiveConfigByModuleName godoc
|
||||
// @Summary Метод получения объекта конфигурации по названию модуля
|
||||
// @Description Возвращает активную конфиграцию по названию модуля
|
||||
// @Tags Конфигурация
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.GetByModuleNameRequest true "название модуля"
|
||||
// @Success 200 {object} entity.Config
|
||||
// @Failure 404 {object} structure.GrpcError "если конфигурация не найдена"
|
||||
@@ -48,13 +50,47 @@ func (c *config) GetActiveConfigByModuleName(request domain.GetByModuleNameReque
|
||||
return config, nil
|
||||
}
|
||||
|
||||
// CreateUpdateConfig godoc
|
||||
// @Summary Метод получения списка конфигураций по ID модуля
|
||||
// @Description Возвращает список конфиграции по ID модуля
|
||||
// @Tags Конфигурация
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.GetByModuleIdRequest true "ID модуля"
|
||||
// @Success 200 {array} domain.ConfigModuleInfo
|
||||
// @Failure 400 {object} structure.GrpcError "если идентификатор не указан"
|
||||
// @Failure 404 {object} structure.GrpcError "если конфигурация не найдена"
|
||||
// @Failure 500 {object} structure.GrpcError
|
||||
// @Router /config/get_configs_by_module_id [POST]
|
||||
func (c *config) GetConfigsByModuleId(request domain.GetByModuleIdRequest) ([]domain.ConfigModuleInfo, error) {
|
||||
var config []entity.Config
|
||||
var configInfo []domain.ConfigModuleInfo
|
||||
|
||||
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
|
||||
config = state.Configs().GetByModuleIds([]string{request.ModuleId})
|
||||
if len(config) == 0 {
|
||||
return
|
||||
}
|
||||
for _, value := range config {
|
||||
configInfo = append(configInfo, domain.ConfigModuleInfo{
|
||||
Config: value,
|
||||
Valid: service.ModuleRegistry.ValidateConfig(value, state),
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
if len(configInfo) == 0 {
|
||||
return nil, status.Errorf(codes.NotFound, "configs for module '%s' not found", request.ModuleId)
|
||||
}
|
||||
|
||||
return configInfo, nil
|
||||
}
|
||||
|
||||
// @Summary Метод обновления конфигурации
|
||||
// @Description Если конфиг с таким id существует, то обновляет данные, если нет, то добавляет данные в базу
|
||||
// В случае обновления рассылает все подключенным модулям актуальную конфигурацию
|
||||
// @Description В случае обновления рассылает всем подключенным модулям актуальную конфигурацию
|
||||
// @Tags Конфигурация
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.CreateUpdateConfigRequest true "объект для сохранения"
|
||||
// @Success 200 {object} domain.ConfigModuleInfo
|
||||
// @Failure 404 {object} structure.GrpcError "если конфигурация не найдена"
|
||||
@@ -66,15 +102,17 @@ func (c *config) CreateUpdateConfig(config domain.CreateUpdateConfigRequest) (*d
|
||||
config.CreatedAt = now
|
||||
config.UpdatedAt = now
|
||||
upsertConfig := cluster.UpsertConfig{
|
||||
Config: config.Config,
|
||||
Unsafe: config.Unsafe,
|
||||
Config: config.Config,
|
||||
Unsafe: config.Unsafe,
|
||||
VersionId: state.GenerateId(),
|
||||
VersionCreateAt: time.Now(),
|
||||
}
|
||||
if config.Id == "" {
|
||||
upsertConfig.Config.Id = state.GenerateId()
|
||||
upsertConfig.Create = true
|
||||
}
|
||||
command := cluster.PrepareUpsertConfigCommand(upsertConfig)
|
||||
err := PerformSyncApplyWithError(command, "UpsertConfigCommand", &response)
|
||||
err := PerformSyncApplyWithError(command, &response)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
} else if response.ErrorDetails != nil {
|
||||
@@ -84,12 +122,11 @@ func (c *config) CreateUpdateConfig(config domain.CreateUpdateConfigRequest) (*d
|
||||
return response.Config, nil
|
||||
}
|
||||
|
||||
// MarkConfigAsActive godoc
|
||||
// @Summary Метод активации конфигурации для модуля
|
||||
// @Description Активирует указанную конфигурацию и деактивирует остальные, возвращает активированную конфигурацию
|
||||
// @Tags Конфигурация
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.ConfigIdRequest true "id конфигурации для изменения"
|
||||
// @Success 200 {object} entity.Config "активированная конфигурация"
|
||||
// @Failure 404 {object} structure.GrpcError "если конфигурация не найдена"
|
||||
@@ -98,19 +135,18 @@ func (c *config) CreateUpdateConfig(config domain.CreateUpdateConfigRequest) (*d
|
||||
func (c *config) MarkConfigAsActive(identity domain.ConfigIdRequest) (*entity.Config, error) {
|
||||
var response entity.Config
|
||||
command := cluster.PrepareActivateConfigCommand(identity.Id, state.GenerateDate())
|
||||
err := PerformSyncApplyWithError(command, "ActivateConfigCommand", &response)
|
||||
err := PerformSyncApplyWithError(command, &response)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &response, nil
|
||||
}
|
||||
|
||||
// DeleteConfigs godoc
|
||||
// @Summary Метод удаления объектов конфигурации по идентификаторам
|
||||
// @Description Возвращает количество удаленных модулей
|
||||
// @Tags Конфигурация
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body []string true "массив идентификаторов конфигураций"
|
||||
// @Success 200 {object} domain.DeleteResponse
|
||||
// @Failure 400 {object} structure.GrpcError "если не указан массив идентификаторов"
|
||||
@@ -125,13 +161,74 @@ func (c *config) DeleteConfigs(identities []string) (*domain.DeleteResponse, err
|
||||
}
|
||||
var response domain.DeleteResponse
|
||||
command := cluster.PrepareDeleteConfigsCommand(identities)
|
||||
err := PerformSyncApply(command, "DeleteConfigsCommand", &response)
|
||||
err := PerformSyncApply(command, &response)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &response, nil
|
||||
}
|
||||
|
||||
// @Summary Метод удаления версии конфигурации
|
||||
// @Description Возвращает количество удаленных версий
|
||||
// @Tags Конфигурация
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.ConfigIdRequest true "id версии конфигурации"
|
||||
// @Success 200 {object} domain.DeleteResponse
|
||||
// @Failure 400 {object} structure.GrpcError "если не указан массив идентификаторов"
|
||||
// @Failure 500 {object} structure.GrpcError
|
||||
// @Router /config/delete_version [POST]
|
||||
func (c *config) DeleteConfigVersion(req domain.ConfigIdRequest) (*domain.DeleteResponse, error) {
|
||||
var response domain.DeleteResponse
|
||||
command := cluster.PrepareDeleteConfigVersionCommand(req.Id)
|
||||
err := PerformSyncApplyWithError(command, &response)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &response, nil
|
||||
}
|
||||
|
||||
// @Summary Метод получение старых версий конфигурации
|
||||
// @Description Возвращает предыдущие версии конфигураций
|
||||
// @Tags Конфигурация
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.ConfigIdRequest true "id конфигурации"
|
||||
// @Success 200 {array} entity.VersionConfig
|
||||
// @Failure 400 {object} structure.GrpcError "если не указан массив идентификаторов"
|
||||
// @Failure 500 {object} structure.GrpcError
|
||||
// @Router /config/get_all_version [POST]
|
||||
func (c *config) GetAllVersion(req domain.ConfigIdRequest) ([]entity.VersionConfig, error) {
|
||||
var response []entity.VersionConfig
|
||||
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
|
||||
response = state.VersionConfig().GetByConfigId(req.Id)
|
||||
})
|
||||
return response, nil
|
||||
}
|
||||
|
||||
// @Summary Метод получение актуальной конфигурации конфигурации
|
||||
// @Description Возвращает актуальную версию конфигурации без дополнительного содержимого (ConfigData)
|
||||
// @Tags Конфигурация
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.ConfigIdRequest true "id конфигурации"
|
||||
// @Success 200 {object} entity.Config
|
||||
// @Failure 400 {object} structure.GrpcError "если не указан идентификатор конфигурации"
|
||||
// @Failure 500 {object} structure.GrpcError
|
||||
// @Router /config/get_config_by_id [POST]
|
||||
func (c *config) GetConfigById(req domain.ConfigIdRequest) (entity.Config, error) {
|
||||
var response []entity.Config
|
||||
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
|
||||
response = state.Configs().GetByIds([]string{req.Id})
|
||||
})
|
||||
|
||||
if len(response) > 0 {
|
||||
return response[0], nil
|
||||
}
|
||||
|
||||
return entity.Config{}, status.Errorf(codes.NotFound, "config with id '%s' not found", req.Id)
|
||||
}
|
||||
|
||||
func NewConfig(rstore *store.Store) *config {
|
||||
return &config{
|
||||
rstore: rstore,
|
||||
|
||||
+13
-7
@@ -17,13 +17,15 @@ func unknownError() error {
|
||||
return status.Error(codes.Unknown, utils.ServiceError)
|
||||
}
|
||||
|
||||
func PerformSyncApply(command []byte, commandName string, responsePtr interface{}) error {
|
||||
func PerformSyncApply(command []byte, responsePtr interface{}) error {
|
||||
applyLogResponse, err := holder.ClusterClient.SyncApply(command)
|
||||
if err != nil {
|
||||
log.Warnf(codes2.SyncApplyError, "apply %s: %v", commandName, err)
|
||||
cmd := cluster.ParseCommand(command)
|
||||
log.Warnf(codes2.SyncApplyError, "apply %s: %v", cmd, err)
|
||||
return unknownError()
|
||||
}
|
||||
if applyLogResponse != nil && applyLogResponse.ApplyError != "" {
|
||||
commandName := cluster.ParseCommand(command).String()
|
||||
log.WithMetadata(map[string]interface{}{
|
||||
"result": string(applyLogResponse.Result),
|
||||
"applyError": applyLogResponse.ApplyError,
|
||||
@@ -31,20 +33,24 @@ func PerformSyncApply(command []byte, commandName string, responsePtr interface{
|
||||
}).Warnf(codes2.SyncApplyError, "apply command")
|
||||
return unknownError()
|
||||
}
|
||||
err = json.Unmarshal(applyLogResponse.Result, responsePtr)
|
||||
if err != nil {
|
||||
return unknownError()
|
||||
if responsePtr != nil {
|
||||
err = json.Unmarshal(applyLogResponse.Result, responsePtr)
|
||||
if err != nil {
|
||||
return unknownError()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func PerformSyncApplyWithError(command []byte, commandName string, responsePtr interface{}) error {
|
||||
func PerformSyncApplyWithError(command []byte, responsePtr interface{}) error {
|
||||
applyLogResponse, err := holder.ClusterClient.SyncApply(command)
|
||||
if err != nil {
|
||||
log.Warnf(codes2.SyncApplyError, "apply %s: %v", commandName, err)
|
||||
cmd := cluster.ParseCommand(command)
|
||||
log.Warnf(codes2.SyncApplyError, "apply %s: %v", cmd, err)
|
||||
return unknownError()
|
||||
}
|
||||
if applyLogResponse != nil && applyLogResponse.ApplyError != "" {
|
||||
commandName := cluster.ParseCommand(command).String()
|
||||
log.WithMetadata(map[string]interface{}{
|
||||
"result": string(applyLogResponse.Result),
|
||||
"applyError": applyLogResponse.ApplyError,
|
||||
|
||||
+31
-6
@@ -8,18 +8,22 @@ import (
|
||||
"isp-config-service/service"
|
||||
"isp-config-service/store"
|
||||
"isp-config-service/store/state"
|
||||
"time"
|
||||
|
||||
"github.com/integration-system/isp-lib/v2/utils"
|
||||
"google.golang.org/grpc/codes"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultEventLifetime = 5 * time.Second
|
||||
)
|
||||
|
||||
var Module *module
|
||||
|
||||
type module struct {
|
||||
rstore *store.Store
|
||||
}
|
||||
|
||||
// GetModulesAggregatedInfo godoc
|
||||
// @Summary Метод получения полной информации о состоянии модуля
|
||||
// @Description Возвращает полное состояние всех модулей в кластере (конфигурация, схема конфигурации, подключенные экземпляры)
|
||||
// @Tags Модули
|
||||
@@ -31,12 +35,11 @@ type module struct {
|
||||
func (c *module) GetModulesAggregatedInfo() ([]domain.ModuleInfo, error) {
|
||||
var response []domain.ModuleInfo
|
||||
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
|
||||
response = service.ModuleRegistryService.GetAggregatedModuleInfo(state)
|
||||
response = service.ModuleRegistry.GetAggregatedModuleInfo(state)
|
||||
})
|
||||
return response, nil
|
||||
}
|
||||
|
||||
// DeleteModules godoc
|
||||
// @Summary Метод удаления объектов модулей по идентификаторам
|
||||
// @Description Возвращает количество удаленных модулей
|
||||
// @Tags Модули
|
||||
@@ -56,16 +59,14 @@ func (*module) DeleteModules(identities []string) (*domain.DeleteResponse, error
|
||||
|
||||
var deleteResponse domain.DeleteResponse
|
||||
command := cluster.PrepareDeleteModulesCommand(identities)
|
||||
err := PerformSyncApply(command, "DeleteCommonConfigsCommand", &deleteResponse)
|
||||
err := PerformSyncApply(command, &deleteResponse)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &deleteResponse, err
|
||||
}
|
||||
|
||||
// GetModuleByName godoc
|
||||
// @Summary Метод получения модуля по имени
|
||||
// @Description Модуль
|
||||
// @Tags Модули
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
@@ -85,6 +86,30 @@ func (c *module) GetModuleByName(req domain.GetByModuleNameRequest) (*entity.Mod
|
||||
return module, nil
|
||||
}
|
||||
|
||||
// @Summary Метод отправки события всем подключенным модулям
|
||||
// @Tags Модули
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.BroadcastEventRequest true "событие"
|
||||
// @Success 200 "OK"
|
||||
// @Failure 500 {object} structure.GrpcError
|
||||
// @Router /module/broadcast_event [POST]
|
||||
func (c *module) BroadcastEvent(req domain.BroadcastEventRequest) error {
|
||||
cmd := cluster.BroadcastEvent{
|
||||
Event: req.Event,
|
||||
ModuleNames: req.ModuleNames,
|
||||
Payload: req.Payload,
|
||||
PerformUntil: time.Now().UTC().Add(defaultEventLifetime),
|
||||
}
|
||||
command := cluster.PrepareBroadcastEventCommand(cmd)
|
||||
err := PerformSyncApply(command, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewModule(rstore *store.Store) *module {
|
||||
return &module{
|
||||
rstore: rstore,
|
||||
|
||||
@@ -14,7 +14,6 @@ type routes struct {
|
||||
rstore *store.Store
|
||||
}
|
||||
|
||||
// GetRoutes godoc
|
||||
// @Summary Метод получения маршрутов
|
||||
// @Description Возвращает все доступные модули
|
||||
// @Tags Роуты
|
||||
|
||||
@@ -15,12 +15,11 @@ type schema struct {
|
||||
rstore *store.Store
|
||||
}
|
||||
|
||||
// GetByModuleId godoc
|
||||
// @Summary Метод получения схемы конфигурации модуля
|
||||
// @Description Возвращает текущую json схему конфигурации модуля
|
||||
// @Tags Схема
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.GetByModuleIdRequest true "идентификатор модуля"
|
||||
// @Success 200 {object} entity.ConfigSchema
|
||||
// @Failure 404 {object} structure.GrpcError "если схема для модуля не найдена"
|
||||
|
||||
+353
-176
@@ -1,5 +1,18 @@
|
||||
basePath: /api/config
|
||||
definitions:
|
||||
domain.BroadcastEventRequest:
|
||||
properties:
|
||||
event:
|
||||
type: string
|
||||
moduleNames:
|
||||
items:
|
||||
type: string
|
||||
type: array
|
||||
payload:
|
||||
items:
|
||||
type: integer
|
||||
type: array
|
||||
type: object
|
||||
domain.CommonConfigLinks:
|
||||
additionalProperties:
|
||||
items:
|
||||
@@ -23,8 +36,6 @@ definitions:
|
||||
properties:
|
||||
id:
|
||||
type: string
|
||||
required:
|
||||
- id
|
||||
type: object
|
||||
domain.ConfigModuleInfo:
|
||||
properties:
|
||||
@@ -38,7 +49,6 @@ definitions:
|
||||
type: string
|
||||
data:
|
||||
$ref: '#/definitions/entity.ConfigData'
|
||||
type: object
|
||||
description:
|
||||
type: string
|
||||
id:
|
||||
@@ -53,15 +63,11 @@ definitions:
|
||||
type: boolean
|
||||
version:
|
||||
type: integer
|
||||
required:
|
||||
- moduleId
|
||||
- name
|
||||
type: object
|
||||
domain.Connection:
|
||||
properties:
|
||||
address:
|
||||
$ref: '#/definitions/structure.AddressConfiguration'
|
||||
type: object
|
||||
endpoints:
|
||||
items:
|
||||
$ref: '#/definitions/structure.EndpointDescriptor'
|
||||
@@ -85,7 +91,6 @@ definitions:
|
||||
type: string
|
||||
data:
|
||||
$ref: '#/definitions/entity.ConfigData'
|
||||
type: object
|
||||
description:
|
||||
type: string
|
||||
id:
|
||||
@@ -100,9 +105,6 @@ definitions:
|
||||
type: string
|
||||
version:
|
||||
type: integer
|
||||
required:
|
||||
- moduleId
|
||||
- name
|
||||
type: object
|
||||
domain.DeleteCommonConfigResponse:
|
||||
properties:
|
||||
@@ -110,7 +112,6 @@ definitions:
|
||||
type: boolean
|
||||
links:
|
||||
$ref: '#/definitions/domain.CommonConfigLinks'
|
||||
type: object
|
||||
type: object
|
||||
domain.DeleteResponse:
|
||||
properties:
|
||||
@@ -121,15 +122,20 @@ definitions:
|
||||
properties:
|
||||
moduleId:
|
||||
type: string
|
||||
required:
|
||||
- moduleId
|
||||
type: object
|
||||
domain.GetByModuleNameRequest:
|
||||
properties:
|
||||
moduleName:
|
||||
type: string
|
||||
required:
|
||||
- moduleName
|
||||
type: object
|
||||
domain.ModuleDependency:
|
||||
properties:
|
||||
id:
|
||||
type: string
|
||||
name:
|
||||
type: string
|
||||
required:
|
||||
type: boolean
|
||||
type: object
|
||||
domain.ModuleInfo:
|
||||
properties:
|
||||
@@ -137,7 +143,6 @@ definitions:
|
||||
type: boolean
|
||||
configSchema:
|
||||
$ref: '#/definitions/schema.Schema'
|
||||
type: object
|
||||
configs:
|
||||
items:
|
||||
$ref: '#/definitions/domain.ConfigModuleInfo'
|
||||
@@ -152,6 +157,10 @@ definitions:
|
||||
type: string
|
||||
name:
|
||||
type: string
|
||||
requiredModules:
|
||||
items:
|
||||
$ref: '#/definitions/domain.ModuleDependency'
|
||||
type: array
|
||||
status:
|
||||
items:
|
||||
$ref: '#/definitions/domain.Connection'
|
||||
@@ -163,7 +172,6 @@ definitions:
|
||||
type: string
|
||||
data:
|
||||
$ref: '#/definitions/entity.ConfigData'
|
||||
type: object
|
||||
description:
|
||||
type: string
|
||||
id:
|
||||
@@ -172,8 +180,6 @@ definitions:
|
||||
type: string
|
||||
updatedAt:
|
||||
type: string
|
||||
required:
|
||||
- name
|
||||
type: object
|
||||
entity.Config:
|
||||
properties:
|
||||
@@ -187,7 +193,6 @@ definitions:
|
||||
type: string
|
||||
data:
|
||||
$ref: '#/definitions/entity.ConfigData'
|
||||
type: object
|
||||
description:
|
||||
type: string
|
||||
id:
|
||||
@@ -200,9 +205,6 @@ definitions:
|
||||
type: string
|
||||
version:
|
||||
type: integer
|
||||
required:
|
||||
- moduleId
|
||||
- name
|
||||
type: object
|
||||
entity.ConfigData:
|
||||
additionalProperties: true
|
||||
@@ -217,7 +219,6 @@ definitions:
|
||||
type: string
|
||||
schema:
|
||||
$ref: '#/definitions/schema.Schema'
|
||||
type: object
|
||||
updatedAt:
|
||||
type: string
|
||||
version:
|
||||
@@ -235,137 +236,24 @@ definitions:
|
||||
type: string
|
||||
name:
|
||||
type: string
|
||||
required:
|
||||
- name
|
||||
type: object
|
||||
entity.VersionConfig:
|
||||
properties:
|
||||
configId:
|
||||
type: string
|
||||
configVersion:
|
||||
type: integer
|
||||
createdAt:
|
||||
type: string
|
||||
data:
|
||||
$ref: '#/definitions/entity.ConfigData'
|
||||
id:
|
||||
type: string
|
||||
type: object
|
||||
jsonschema.Definitions:
|
||||
additionalProperties:
|
||||
$ref: '#/definitions/jsonschema.Type'
|
||||
type: object
|
||||
jsonschema.Schema:
|
||||
properties:
|
||||
$ref:
|
||||
description: section 7
|
||||
type: string
|
||||
$schema:
|
||||
description: RFC draft-wright-json-schema-00
|
||||
type: string
|
||||
additionalItems:
|
||||
description: section 5.9
|
||||
type: integer
|
||||
additionalProperties:
|
||||
description: section 5.18
|
||||
type: string
|
||||
allOf:
|
||||
description: section 5.22
|
||||
items:
|
||||
type: integer
|
||||
type: array
|
||||
anyOf:
|
||||
description: section 5.23
|
||||
items:
|
||||
type: integer
|
||||
type: array
|
||||
binaryEncoding:
|
||||
description: section 4.3
|
||||
type: string
|
||||
default:
|
||||
description: section 6.2
|
||||
type: object
|
||||
definitions:
|
||||
$ref: '#/definitions/jsonschema.Definitions'
|
||||
type: object
|
||||
dependencies:
|
||||
additionalProperties:
|
||||
$ref: '#/definitions/jsonschema.Type'
|
||||
description: section 5.19
|
||||
type: object
|
||||
description:
|
||||
description: section 6.1
|
||||
type: string
|
||||
enum:
|
||||
description: section 5.20
|
||||
items:
|
||||
type: object
|
||||
type: array
|
||||
exclusiveMaximum:
|
||||
description: section 5.3
|
||||
type: boolean
|
||||
exclusiveMinimum:
|
||||
description: section 5.5
|
||||
type: boolean
|
||||
format:
|
||||
description: section 7
|
||||
type: string
|
||||
items:
|
||||
description: section 5.9
|
||||
type: integer
|
||||
maxItems:
|
||||
description: section 5.10
|
||||
type: integer
|
||||
maxLength:
|
||||
description: section 5.6
|
||||
type: integer
|
||||
maxProperties:
|
||||
description: section 5.13
|
||||
type: integer
|
||||
maximum:
|
||||
description: section 5.2
|
||||
type: integer
|
||||
media:
|
||||
description: RFC draft-wright-json-schema-hyperschema-00, section 4
|
||||
type: integer
|
||||
minItems:
|
||||
description: section 5.11
|
||||
type: integer
|
||||
minLength:
|
||||
description: section 5.7
|
||||
type: integer
|
||||
minProperties:
|
||||
description: section 5.14
|
||||
type: integer
|
||||
minimum:
|
||||
description: section 5.4
|
||||
type: integer
|
||||
multipleOf:
|
||||
description: RFC draft-wright-json-schema-validation-00, section 5
|
||||
type: integer
|
||||
not:
|
||||
description: section 5.25
|
||||
type: integer
|
||||
oneOf:
|
||||
description: section 5.24
|
||||
items:
|
||||
type: integer
|
||||
type: array
|
||||
pattern:
|
||||
description: section 5.8
|
||||
type: string
|
||||
patternProperties:
|
||||
additionalProperties:
|
||||
$ref: '#/definitions/jsonschema.Type'
|
||||
description: section 5.17
|
||||
type: object
|
||||
properties:
|
||||
additionalProperties:
|
||||
$ref: '#/definitions/jsonschema.Type'
|
||||
description: section 5.16
|
||||
type: object
|
||||
required:
|
||||
description: section 5.15
|
||||
items:
|
||||
type: string
|
||||
type: array
|
||||
title:
|
||||
description: RFC draft-wright-json-schema-validation-00, section 6, 7
|
||||
type: string
|
||||
type:
|
||||
description: section 5.21
|
||||
type: string
|
||||
uniqueItems:
|
||||
description: section 5.12
|
||||
type: boolean
|
||||
type: object
|
||||
jsonschema.Type:
|
||||
properties:
|
||||
$ref:
|
||||
@@ -375,31 +263,33 @@ definitions:
|
||||
description: RFC draft-wright-json-schema-00
|
||||
type: string
|
||||
additionalItems:
|
||||
allOf:
|
||||
- $ref: '#/definitions/jsonschema.Type'
|
||||
description: section 5.9
|
||||
type: integer
|
||||
additionalProperties:
|
||||
description: section 5.18
|
||||
type: string
|
||||
items:
|
||||
type: integer
|
||||
type: array
|
||||
allOf:
|
||||
description: section 5.22
|
||||
items:
|
||||
type: integer
|
||||
$ref: '#/definitions/jsonschema.Type'
|
||||
type: array
|
||||
anyOf:
|
||||
description: section 5.23
|
||||
items:
|
||||
type: integer
|
||||
$ref: '#/definitions/jsonschema.Type'
|
||||
type: array
|
||||
binaryEncoding:
|
||||
description: section 4.3
|
||||
type: string
|
||||
default:
|
||||
description: section 6.2
|
||||
type: object
|
||||
definitions:
|
||||
$ref: '#/definitions/jsonschema.Definitions'
|
||||
allOf:
|
||||
- $ref: '#/definitions/jsonschema.Definitions'
|
||||
description: section 5.26
|
||||
type: object
|
||||
dependencies:
|
||||
additionalProperties:
|
||||
$ref: '#/definitions/jsonschema.Type'
|
||||
@@ -410,8 +300,7 @@ definitions:
|
||||
type: string
|
||||
enum:
|
||||
description: section 5.20
|
||||
items:
|
||||
type: object
|
||||
items: {}
|
||||
type: array
|
||||
exclusiveMaximum:
|
||||
description: section 5.3
|
||||
@@ -423,8 +312,9 @@ definitions:
|
||||
description: section 7
|
||||
type: string
|
||||
items:
|
||||
allOf:
|
||||
- $ref: '#/definitions/jsonschema.Type'
|
||||
description: section 5.9
|
||||
type: integer
|
||||
maxItems:
|
||||
description: section 5.10
|
||||
type: integer
|
||||
@@ -438,8 +328,9 @@ definitions:
|
||||
description: section 5.2
|
||||
type: integer
|
||||
media:
|
||||
allOf:
|
||||
- $ref: '#/definitions/jsonschema.Type'
|
||||
description: RFC draft-wright-json-schema-hyperschema-00, section 4
|
||||
type: integer
|
||||
minItems:
|
||||
description: section 5.11
|
||||
type: integer
|
||||
@@ -456,12 +347,13 @@ definitions:
|
||||
description: RFC draft-wright-json-schema-validation-00, section 5
|
||||
type: integer
|
||||
not:
|
||||
allOf:
|
||||
- $ref: '#/definitions/jsonschema.Type'
|
||||
description: section 5.25
|
||||
type: integer
|
||||
oneOf:
|
||||
description: section 5.24
|
||||
items:
|
||||
type: integer
|
||||
$ref: '#/definitions/jsonschema.Type'
|
||||
type: array
|
||||
pattern:
|
||||
description: section 5.8
|
||||
@@ -492,7 +384,132 @@ definitions:
|
||||
type: boolean
|
||||
type: object
|
||||
schema.Schema:
|
||||
$ref: '#/definitions/jsonschema.Schema'
|
||||
properties:
|
||||
$ref:
|
||||
description: section 7
|
||||
type: string
|
||||
$schema:
|
||||
description: RFC draft-wright-json-schema-00
|
||||
type: string
|
||||
additionalItems:
|
||||
allOf:
|
||||
- $ref: '#/definitions/jsonschema.Type'
|
||||
description: section 5.9
|
||||
additionalProperties:
|
||||
description: section 5.18
|
||||
items:
|
||||
type: integer
|
||||
type: array
|
||||
allOf:
|
||||
description: section 5.22
|
||||
items:
|
||||
$ref: '#/definitions/jsonschema.Type'
|
||||
type: array
|
||||
anyOf:
|
||||
description: section 5.23
|
||||
items:
|
||||
$ref: '#/definitions/jsonschema.Type'
|
||||
type: array
|
||||
binaryEncoding:
|
||||
description: section 4.3
|
||||
type: string
|
||||
default:
|
||||
description: section 6.2
|
||||
definitions:
|
||||
$ref: '#/definitions/jsonschema.Definitions'
|
||||
dependencies:
|
||||
additionalProperties:
|
||||
$ref: '#/definitions/jsonschema.Type'
|
||||
description: section 5.19
|
||||
type: object
|
||||
description:
|
||||
description: section 6.1
|
||||
type: string
|
||||
enum:
|
||||
description: section 5.20
|
||||
items: {}
|
||||
type: array
|
||||
exclusiveMaximum:
|
||||
description: section 5.3
|
||||
type: boolean
|
||||
exclusiveMinimum:
|
||||
description: section 5.5
|
||||
type: boolean
|
||||
format:
|
||||
description: section 7
|
||||
type: string
|
||||
items:
|
||||
allOf:
|
||||
- $ref: '#/definitions/jsonschema.Type'
|
||||
description: section 5.9
|
||||
maxItems:
|
||||
description: section 5.10
|
||||
type: integer
|
||||
maxLength:
|
||||
description: section 5.6
|
||||
type: integer
|
||||
maxProperties:
|
||||
description: section 5.13
|
||||
type: integer
|
||||
maximum:
|
||||
description: section 5.2
|
||||
type: integer
|
||||
media:
|
||||
allOf:
|
||||
- $ref: '#/definitions/jsonschema.Type'
|
||||
description: RFC draft-wright-json-schema-hyperschema-00, section 4
|
||||
minItems:
|
||||
description: section 5.11
|
||||
type: integer
|
||||
minLength:
|
||||
description: section 5.7
|
||||
type: integer
|
||||
minProperties:
|
||||
description: section 5.14
|
||||
type: integer
|
||||
minimum:
|
||||
description: section 5.4
|
||||
type: integer
|
||||
multipleOf:
|
||||
description: RFC draft-wright-json-schema-validation-00, section 5
|
||||
type: integer
|
||||
not:
|
||||
allOf:
|
||||
- $ref: '#/definitions/jsonschema.Type'
|
||||
description: section 5.25
|
||||
oneOf:
|
||||
description: section 5.24
|
||||
items:
|
||||
$ref: '#/definitions/jsonschema.Type'
|
||||
type: array
|
||||
pattern:
|
||||
description: section 5.8
|
||||
type: string
|
||||
patternProperties:
|
||||
additionalProperties:
|
||||
$ref: '#/definitions/jsonschema.Type'
|
||||
description: section 5.17
|
||||
type: object
|
||||
properties:
|
||||
additionalProperties:
|
||||
$ref: '#/definitions/jsonschema.Type'
|
||||
description: section 5.16
|
||||
type: object
|
||||
required:
|
||||
description: section 5.15
|
||||
items:
|
||||
type: string
|
||||
type: array
|
||||
title:
|
||||
description: RFC draft-wright-json-schema-validation-00, section 6, 7
|
||||
type: string
|
||||
type:
|
||||
description: section 5.21
|
||||
type: string
|
||||
uniqueItems:
|
||||
description: section 5.12
|
||||
type: boolean
|
||||
type: object
|
||||
structure.AddressConfiguration:
|
||||
properties:
|
||||
ip:
|
||||
@@ -504,7 +521,6 @@ definitions:
|
||||
properties:
|
||||
address:
|
||||
$ref: '#/definitions/structure.AddressConfiguration'
|
||||
type: object
|
||||
endpoints:
|
||||
items:
|
||||
$ref: '#/definitions/structure.EndpointDescriptor'
|
||||
@@ -513,6 +529,10 @@ definitions:
|
||||
type: string
|
||||
moduleName:
|
||||
type: string
|
||||
requiredModules:
|
||||
items:
|
||||
$ref: '#/definitions/structure.ModuleDependency'
|
||||
type: array
|
||||
version:
|
||||
type: string
|
||||
type: object
|
||||
@@ -527,20 +547,24 @@ definitions:
|
||||
type: string
|
||||
userAuthRequired:
|
||||
type: boolean
|
||||
required:
|
||||
- path
|
||||
type: object
|
||||
structure.GrpcError:
|
||||
properties:
|
||||
details:
|
||||
items:
|
||||
type: object
|
||||
items: {}
|
||||
type: array
|
||||
errorCode:
|
||||
type: string
|
||||
errorMessage:
|
||||
type: string
|
||||
type: object
|
||||
structure.ModuleDependency:
|
||||
properties:
|
||||
name:
|
||||
type: string
|
||||
required:
|
||||
type: boolean
|
||||
type: object
|
||||
host: localhost:9003
|
||||
info:
|
||||
contact: {}
|
||||
@@ -548,7 +572,7 @@ info:
|
||||
license:
|
||||
name: GNU GPL v3.0
|
||||
title: ISP configuration service
|
||||
version: 2.0.0
|
||||
version: 2.4.1
|
||||
paths:
|
||||
/common_config/compile:
|
||||
post:
|
||||
@@ -576,8 +600,9 @@ paths:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Если конфиг с таким id существует, то обновляет данные, если нет,
|
||||
то добавляет данные в базу
|
||||
description: |-
|
||||
Если конфиг с таким id существует, то обновляет данные, если нет, то добавляет данные в базу
|
||||
В случае обновления рассылает всем подключенным модулям актуальную конфигурацию
|
||||
parameters:
|
||||
- description: объект для сохранения
|
||||
in: body
|
||||
@@ -675,8 +700,9 @@ paths:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Если конфиг с таким id существует, то обновляет данные, если нет,
|
||||
то добавляет данные в базу
|
||||
description: |-
|
||||
Если конфиг с таким id существует, то обновляет данные, если нет, то добавляет данные в базу
|
||||
В случае обновления рассылает всем подключенным модулям актуальную конфигурацию
|
||||
parameters:
|
||||
- description: объект для сохранения
|
||||
in: body
|
||||
@@ -734,6 +760,36 @@ paths:
|
||||
summary: Метод удаления объектов конфигурации по идентификаторам
|
||||
tags:
|
||||
- Конфигурация
|
||||
/config/delete_version:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Возвращает количество удаленных версий
|
||||
parameters:
|
||||
- description: id версии конфигурации
|
||||
in: body
|
||||
name: body
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/domain.ConfigIdRequest'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/domain.DeleteResponse'
|
||||
"400":
|
||||
description: если не указан массив идентификаторов
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
summary: Метод удаления версии конфигурации
|
||||
tags:
|
||||
- Конфигурация
|
||||
/config/get_active_config_by_module_name:
|
||||
post:
|
||||
consumes:
|
||||
@@ -764,6 +820,105 @@ paths:
|
||||
summary: Метод получения объекта конфигурации по названию модуля
|
||||
tags:
|
||||
- Конфигурация
|
||||
/config/get_all_version:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Возвращает предыдущие версии конфигураций
|
||||
parameters:
|
||||
- description: id конфигурации
|
||||
in: body
|
||||
name: body
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/domain.ConfigIdRequest'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
items:
|
||||
$ref: '#/definitions/entity.VersionConfig'
|
||||
type: array
|
||||
"400":
|
||||
description: если не указан массив идентификаторов
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
summary: Метод получение старых версий конфигурации
|
||||
tags:
|
||||
- Конфигурация
|
||||
/config/get_config_by_id:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Возвращает актуальную версию конфигурации без дополнительного содержимого
|
||||
(ConfigData)
|
||||
parameters:
|
||||
- description: id конфигурации
|
||||
in: body
|
||||
name: body
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/domain.ConfigIdRequest'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/entity.Config'
|
||||
"400":
|
||||
description: если не указан идентификатор конфигурации
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
summary: Метод получение актуальной конфигурации конфигурации
|
||||
tags:
|
||||
- Конфигурация
|
||||
/config/get_configs_by_module_id:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Возвращает список конфиграции по ID модуля
|
||||
parameters:
|
||||
- description: ID модуля
|
||||
in: body
|
||||
name: body
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/domain.GetByModuleIdRequest'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
items:
|
||||
$ref: '#/definitions/domain.ConfigModuleInfo'
|
||||
type: array
|
||||
"400":
|
||||
description: если идентификатор не указан
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
"404":
|
||||
description: если конфигурация не найдена
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
summary: Метод получения списка конфигураций по ID модуля
|
||||
tags:
|
||||
- Конфигурация
|
||||
/config/mark_config_as_active:
|
||||
post:
|
||||
consumes:
|
||||
@@ -795,6 +950,29 @@ paths:
|
||||
summary: Метод активации конфигурации для модуля
|
||||
tags:
|
||||
- Конфигурация
|
||||
/module/broadcast_event:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
parameters:
|
||||
- description: событие
|
||||
in: body
|
||||
name: body
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/domain.BroadcastEventRequest'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
summary: Метод отправки события всем подключенным модулям
|
||||
tags:
|
||||
- Модули
|
||||
/module/delete_module:
|
||||
post:
|
||||
consumes:
|
||||
@@ -827,7 +1005,6 @@ paths:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Модуль
|
||||
parameters:
|
||||
- description: название модуля
|
||||
in: body
|
||||
|
||||
+11
-1
@@ -1,6 +1,10 @@
|
||||
package domain
|
||||
|
||||
import "isp-config-service/entity"
|
||||
import (
|
||||
json2 "encoding/json"
|
||||
|
||||
"isp-config-service/entity"
|
||||
)
|
||||
|
||||
type ConfigIdRequest struct {
|
||||
Id string `json:"id" valid:"required~Required"`
|
||||
@@ -19,6 +23,12 @@ type GetByModuleNameRequest struct {
|
||||
ModuleName string `valid:"required~Required"`
|
||||
}
|
||||
|
||||
type BroadcastEventRequest struct {
|
||||
ModuleNames []string `valid:"required~Required"`
|
||||
Event string `valid:"required~Required"`
|
||||
Payload json2.RawMessage
|
||||
}
|
||||
|
||||
type CreateUpdateConfigRequest struct {
|
||||
entity.Config
|
||||
Unsafe bool
|
||||
|
||||
+11
-4
@@ -19,19 +19,26 @@ type ModuleInfo struct {
|
||||
CreatedAt time.Time
|
||||
LastConnectedAt time.Time
|
||||
LastDisconnectedAt time.Time
|
||||
Configs []ConfigModuleInfo `json:",omitempty"`
|
||||
ConfigSchema *schema.Schema `json:",omitempty"`
|
||||
Status []Connection `json:",omitempty"`
|
||||
Configs []ConfigModuleInfo
|
||||
ConfigSchema *schema.Schema
|
||||
Status []Connection
|
||||
RequiredModules []ModuleDependency
|
||||
}
|
||||
|
||||
type Connection struct {
|
||||
LibVersion string
|
||||
Version string
|
||||
Address structure.AddressConfiguration
|
||||
Endpoints []structure.EndpointDescriptor `json:",omitempty"`
|
||||
Endpoints []structure.EndpointDescriptor
|
||||
EstablishedAt time.Time
|
||||
}
|
||||
|
||||
type ModuleDependency struct {
|
||||
Id string
|
||||
Name string
|
||||
Required bool
|
||||
}
|
||||
|
||||
type CommonConfigLinks map[string][]string
|
||||
|
||||
type CompiledConfigResponse map[string]interface{}
|
||||
|
||||
+11
-11
@@ -10,33 +10,33 @@ type ConfigData map[string]interface{}
|
||||
|
||||
type Config struct {
|
||||
//nolint
|
||||
tableName string `sql:"?db_schema.configs" json:"-"`
|
||||
tableName string `pg:"?db_schema.configs" json:"-"`
|
||||
Id string `json:"id"`
|
||||
Name string `json:"name" valid:"required~Required"`
|
||||
CommonConfigs []string `json:"commonConfigs" pg:",array"`
|
||||
Description string `json:"description"`
|
||||
ModuleId string `json:"moduleId" valid:"required~Required"`
|
||||
Version int32 `json:"version" sql:",null"`
|
||||
Active bool `json:"active" sql:",null"`
|
||||
CreatedAt time.Time `json:"createdAt" sql:",null"`
|
||||
UpdatedAt time.Time `json:"updatedAt" sql:",null"`
|
||||
Data ConfigData `json:"data" sql:",notnull"`
|
||||
Version int32 `json:"version" pg:",null"`
|
||||
Active bool `json:"active" pg:",null"`
|
||||
CreatedAt time.Time `json:"createdAt" pg:",null"`
|
||||
UpdatedAt time.Time `json:"updatedAt" pg:",null"`
|
||||
Data ConfigData `json:"data,omitempty" pg:",notnull"`
|
||||
}
|
||||
|
||||
type CommonConfig struct {
|
||||
//nolint
|
||||
tableName string `sql:"?db_schema.common_configs" json:"-"`
|
||||
tableName string `pg:"?db_schema.common_configs" json:"-"`
|
||||
Id string `json:"id"`
|
||||
Name string `json:"name" valid:"required~Required"`
|
||||
Description string `json:"description"`
|
||||
CreatedAt time.Time `json:"createdAt" sql:",null"`
|
||||
UpdatedAt time.Time `json:"updatedAt" sql:",null"`
|
||||
Data ConfigData `json:"data" sql:",notnull"`
|
||||
CreatedAt time.Time `json:"createdAt" pg:",null"`
|
||||
UpdatedAt time.Time `json:"updatedAt" pg:",null"`
|
||||
Data ConfigData `json:"data" pg:",notnull"`
|
||||
}
|
||||
|
||||
type ConfigSchema struct {
|
||||
//nolint
|
||||
tableName string `sql:"?db_schema.config_schemas" json:"-"`
|
||||
tableName string `pg:"?db_schema.config_schemas" json:"-"`
|
||||
Id string `json:"id"`
|
||||
Version string
|
||||
ModuleId string
|
||||
|
||||
+2
-2
@@ -4,10 +4,10 @@ import "time"
|
||||
|
||||
type Module struct {
|
||||
//nolint
|
||||
tableName string `sql:"?db_schema.modules" json:"-"`
|
||||
tableName string `pg:"?db_schema.modules" json:"-"`
|
||||
Id string `json:"id"`
|
||||
Name string `json:"name" valid:"required~Required"`
|
||||
CreatedAt time.Time `json:"createdAt" sql:",null"`
|
||||
CreatedAt time.Time `json:"createdAt" pg:",null"`
|
||||
LastConnectedAt time.Time `json:"lastConnectedAt"`
|
||||
LastDisconnectedAt time.Time `json:"lastDisconnectedAt"`
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package entity
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type VersionConfig struct {
|
||||
//nolint
|
||||
tableName string `pg:"?db_schema.version_config" json:"-"`
|
||||
Id string
|
||||
ConfigId string
|
||||
ConfigVersion int32
|
||||
Data ConfigData `json:"data,omitempty" pg:",notnull"`
|
||||
CreatedAt time.Time
|
||||
}
|
||||
@@ -1,25 +1,102 @@
|
||||
module isp-config-service
|
||||
|
||||
go 1.13
|
||||
go 1.19
|
||||
|
||||
require (
|
||||
github.com/asaskevich/govalidator v0.0.0-20180315120708-ccb8e960c48f
|
||||
github.com/cenkalti/backoff/v4 v4.0.0
|
||||
github.com/go-pg/pg/v9 v9.1.3
|
||||
github.com/hashicorp/raft v1.1.2
|
||||
github.com/hashicorp/raft-boltdb v0.0.0-20191021154308-4207f1bf0617
|
||||
github.com/integration-system/bellows v0.0.0-20190821124023-244325e8836c
|
||||
github.com/integration-system/isp-etp-go/v2 v2.1.0
|
||||
github.com/integration-system/isp-lib-test v1.5.0
|
||||
github.com/integration-system/isp-lib/v2 v2.2.0
|
||||
github.com/integration-system/isp-log v1.1.2
|
||||
github.com/integration-system/net-mux v1.0.0
|
||||
github.com/json-iterator/go v1.1.9
|
||||
github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d
|
||||
github.com/cenkalti/backoff/v4 v4.2.0
|
||||
github.com/go-pg/pg/v9 v9.2.1
|
||||
github.com/hashicorp/raft v1.3.11
|
||||
github.com/hashicorp/raft-boltdb/v2 v2.2.2
|
||||
github.com/integration-system/bellows v1.0.1
|
||||
github.com/integration-system/isp-etp-go/v2 v2.1.3
|
||||
github.com/integration-system/isp-lib/v2 v2.11.0
|
||||
github.com/integration-system/isp-log v1.2.0
|
||||
github.com/integration-system/net-mux v1.0.1
|
||||
github.com/json-iterator/go v1.1.12
|
||||
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/satori/go.uuid v1.2.0
|
||||
github.com/stretchr/testify v1.5.1
|
||||
github.com/thecodeteam/goodbye v0.0.0-20170927022442-a83968bda2d3
|
||||
github.com/xeipuuv/gojsonschema v1.2.0
|
||||
google.golang.org/grpc v1.27.1
|
||||
google.golang.org/grpc v1.51.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/KyleBanks/depth v1.2.1 // indirect
|
||||
github.com/andybalholm/brotli v1.0.4 // indirect
|
||||
github.com/armon/go-metrics v0.4.1 // indirect
|
||||
github.com/boltdb/bolt v1.3.1 // indirect
|
||||
github.com/buaazp/fasthttprouter v0.1.1 // indirect
|
||||
github.com/codemodus/kace v0.5.1 // indirect
|
||||
github.com/fatih/color v1.13.0 // indirect
|
||||
github.com/fsnotify/fsnotify v1.6.0 // indirect
|
||||
github.com/go-openapi/jsonpointer v0.19.5 // indirect
|
||||
github.com/go-openapi/jsonreference v0.20.0 // indirect
|
||||
github.com/go-openapi/spec v0.20.7 // indirect
|
||||
github.com/go-openapi/swag v0.22.3 // indirect
|
||||
github.com/go-pg/zerochecker v0.2.0 // indirect
|
||||
github.com/golang/protobuf v1.5.2 // indirect
|
||||
github.com/gorilla/websocket v1.4.2 // indirect
|
||||
github.com/hashicorp/errwrap v1.1.0 // indirect
|
||||
github.com/hashicorp/go-hclog v1.3.1 // indirect
|
||||
github.com/hashicorp/go-immutable-radix v1.3.1 // indirect
|
||||
github.com/hashicorp/go-msgpack v0.5.5 // indirect
|
||||
github.com/hashicorp/go-multierror v1.1.1 // indirect
|
||||
github.com/hashicorp/go-uuid v1.0.1 // indirect
|
||||
github.com/hashicorp/golang-lru v0.5.4 // indirect
|
||||
github.com/hashicorp/hcl v1.0.0 // indirect
|
||||
github.com/integration-system/go-cmp v0.0.0-20190131081942-ac5582987a2f // indirect
|
||||
github.com/integration-system/jsonschema v1.0.1 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/josharian/intern v1.0.0 // indirect
|
||||
github.com/klauspost/compress v1.15.12 // indirect
|
||||
github.com/lib/pq v1.10.7 // indirect
|
||||
github.com/magiconair/properties v1.8.6 // indirect
|
||||
github.com/mailru/easyjson v0.7.7 // indirect
|
||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||
github.com/mattn/go-isatty v0.0.16 // indirect
|
||||
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/onsi/ginkgo v1.15.0 // indirect
|
||||
github.com/onsi/gomega v1.10.5 // indirect
|
||||
github.com/pelletier/go-toml v1.9.5 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.0.6 // indirect
|
||||
github.com/pressly/goose v2.7.0+incompatible // indirect
|
||||
github.com/profefe/profefe v0.0.0-20210412073930-18342f204d75 // indirect
|
||||
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect
|
||||
github.com/segmentio/asm v1.2.0 // indirect
|
||||
github.com/segmentio/encoding v0.3.6 // indirect
|
||||
github.com/sirupsen/logrus v1.9.0 // indirect
|
||||
github.com/spf13/afero v1.9.3 // indirect
|
||||
github.com/spf13/cast v1.5.0 // indirect
|
||||
github.com/spf13/jwalterweatherman v1.1.0 // indirect
|
||||
github.com/spf13/pflag v1.0.5 // indirect
|
||||
github.com/spf13/viper v1.14.0 // indirect
|
||||
github.com/subosito/gotenv v1.4.1 // indirect
|
||||
github.com/swaggo/files v0.0.0-20220728132757-551d4a08d97a // indirect
|
||||
github.com/swaggo/http-swagger v1.3.3 // indirect
|
||||
github.com/swaggo/swag v1.8.8 // indirect
|
||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||
github.com/valyala/fasthttp v1.43.0 // indirect
|
||||
github.com/vmihailenco/bufpool v0.1.11 // indirect
|
||||
github.com/vmihailenco/msgpack/v4 v4.3.12 // indirect
|
||||
github.com/vmihailenco/tagparser v0.1.2 // indirect
|
||||
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect
|
||||
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
|
||||
go.etcd.io/bbolt v1.3.6 // indirect
|
||||
golang.org/x/crypto v0.3.0 // indirect
|
||||
golang.org/x/lint v0.0.0-20210508222113-6edffad5e616 // indirect
|
||||
golang.org/x/net v0.2.0 // indirect
|
||||
golang.org/x/sys v0.2.0 // indirect
|
||||
golang.org/x/text v0.4.0 // indirect
|
||||
golang.org/x/tools v0.3.0 // indirect
|
||||
google.golang.org/appengine v1.6.7 // indirect
|
||||
google.golang.org/genproto v0.0.0-20221118155620-16455021b5e6 // indirect
|
||||
google.golang.org/protobuf v1.28.1 // indirect
|
||||
gopkg.in/ini.v1 v1.67.0 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
mellium.im/sasl v0.3.0 // indirect
|
||||
nhooyr.io/websocket v1.8.7 // indirect
|
||||
)
|
||||
+12
-1
@@ -1,4 +1,4 @@
|
||||
//nolint lll
|
||||
//nolint:lll
|
||||
package helper
|
||||
|
||||
import (
|
||||
@@ -13,11 +13,17 @@ type Handlers struct {
|
||||
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"`
|
||||
BroadcastEvent func(req domain.BroadcastEventRequest) error `method:"broadcast_event" group:"module" inner:"true"`
|
||||
|
||||
// ===== CONFIG =====
|
||||
GetActiveConfigByModuleName func(request domain.GetByModuleNameRequest) (*entity.Config, error) `method:"get_active_config_by_module_name" group:"config" inner:"true"`
|
||||
GetConfigsByModuleId func(request domain.GetByModuleIdRequest) ([]domain.ConfigModuleInfo, error) `method:"get_configs_by_module_id" group:"config" inner:"true"`
|
||||
CreateUpdateConfig func(config domain.CreateUpdateConfigRequest) (*domain.ConfigModuleInfo, error) `method:"create_update_config" group:"config" inner:"true"`
|
||||
MarkConfigAsActive func(identity domain.ConfigIdRequest) (*entity.Config, error) `method:"mark_config_as_active" group:"config" inner:"true"`
|
||||
DeleteConfig func(identities []string) (*domain.DeleteResponse, error) `method:"delete_config" group:"config" inner:"true"`
|
||||
DeleteVersion func(identity domain.ConfigIdRequest) (*domain.DeleteResponse, error) `method:"delete_version" group:"config" inner:"true"`
|
||||
GetAllVersion func(identity domain.ConfigIdRequest) ([]entity.VersionConfig, error) `method:"get_all_version" group:"config" inner:"true"`
|
||||
GetConfigByID func(identity domain.ConfigIdRequest) (entity.Config, error) `method:"get_config_by_id" group:"config" inner:"true"`
|
||||
|
||||
// ===== COMMON CONFIG =====
|
||||
GetCommonConfigs func(identities []string) []entity.CommonConfig `method:"get_configs" group:"common_config" inner:"true"`
|
||||
@@ -38,11 +44,16 @@ func GetHandlers() *Handlers {
|
||||
DeleteModules: controller.Module.DeleteModules,
|
||||
GetModulesInfo: controller.Module.GetModulesAggregatedInfo,
|
||||
GetModuleByName: controller.Module.GetModuleByName,
|
||||
BroadcastEvent: controller.Module.BroadcastEvent,
|
||||
|
||||
GetActiveConfigByModuleName: controller.Config.GetActiveConfigByModuleName,
|
||||
GetConfigsByModuleId: controller.Config.GetConfigsByModuleId,
|
||||
CreateUpdateConfig: controller.Config.CreateUpdateConfig,
|
||||
MarkConfigAsActive: controller.Config.MarkConfigAsActive,
|
||||
DeleteConfig: controller.Config.DeleteConfigs,
|
||||
DeleteVersion: controller.Config.DeleteConfigVersion,
|
||||
GetAllVersion: controller.Config.GetAllVersion,
|
||||
GetConfigByID: controller.Config.GetConfigById,
|
||||
|
||||
GetCommonConfigs: controller.CommonConfig.GetConfigs,
|
||||
CreateUpdateCommonConfig: controller.CommonConfig.CreateUpdateConfig,
|
||||
|
||||
@@ -6,16 +6,19 @@ import (
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/integration-system/isp-etp-go/v2"
|
||||
"github.com/integration-system/isp-lib/v2/backend"
|
||||
"github.com/integration-system/isp-lib/v2/bootstrap"
|
||||
"github.com/integration-system/isp-lib/v2/config"
|
||||
"github.com/integration-system/isp-lib/v2/metric"
|
||||
"github.com/integration-system/isp-lib/v2/structure"
|
||||
"github.com/integration-system/isp-lib/v2/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"
|
||||
"isp-config-service/conf"
|
||||
@@ -38,8 +41,7 @@ const (
|
||||
var (
|
||||
version = "0.1.0"
|
||||
|
||||
shutdownChan = make(chan struct{})
|
||||
muxer mux.Mux
|
||||
muxer mux.Mux
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -50,7 +52,7 @@ func init() {
|
||||
}
|
||||
|
||||
// @title ISP configuration service
|
||||
// @version 2.0.0
|
||||
// @version 2.4.1
|
||||
// @description Сервис управления конфигурацией модулей ISP кластера
|
||||
|
||||
// @license.name GNU GPL v3.0
|
||||
@@ -58,10 +60,9 @@ func init() {
|
||||
// @host localhost:9003
|
||||
// @BasePath /api/config
|
||||
|
||||
//go:generate swag init --parseVendor
|
||||
//go:generate rm -f docs/docs.go docs/swagger.json
|
||||
//go:generate swag init --parseDependency
|
||||
//go:generate rm -f docs/swagger.json
|
||||
func main() {
|
||||
ctx := context.Background()
|
||||
cfg := config.Get().(*conf.Configuration)
|
||||
handlers := helper.GetHandlers()
|
||||
endpoints := backend.GetEndpoints(cfg.ModuleName, handlers)
|
||||
@@ -83,11 +84,12 @@ func main() {
|
||||
|
||||
connectionReadLimit := defaultWsConnectionReadLimit
|
||||
if cfg.WS.WsConnectionReadLimitKB > 0 {
|
||||
//nolint gomnd
|
||||
//nolint:gomnd
|
||||
connectionReadLimit = cfg.WS.WsConnectionReadLimitKB << 10
|
||||
}
|
||||
cluster.WsConnectionReadLimit = connectionReadLimit
|
||||
|
||||
cfg.Database.Password = fmt.Sprintf("%s%s", cfg.Database.Password, os.Getenv("DB_PASSPART"))
|
||||
model.DbClient.ReceiveConfiguration(cfg.Database)
|
||||
|
||||
httpListener, raftListener, err := initMultiplexer(cfg.WS.Rest)
|
||||
@@ -96,14 +98,14 @@ func main() {
|
||||
}
|
||||
|
||||
_, raftStore := initRaft(raftListener, cfg.Cluster, declaration)
|
||||
initWebsocket(ctx, connectionReadLimit, httpListener, raftStore)
|
||||
initWebsocket(connectionReadLimit, httpListener, raftStore)
|
||||
initGrpc(cfg.WS.Grpc, raftStore)
|
||||
|
||||
defer goodbye.Exit(ctx, -1)
|
||||
goodbye.Notify(ctx)
|
||||
goodbye.Register(onShutdown)
|
||||
metric.InitProfiling(cfg.ModuleName)
|
||||
metric.InitCollectors(cfg.Metrics, structure.MetricConfiguration{})
|
||||
metric.InitHttpServer(cfg.Metrics)
|
||||
|
||||
<-shutdownChan
|
||||
gracefulShutdown()
|
||||
}
|
||||
|
||||
func initMultiplexer(addressConfiguration structure.AddressConfiguration) (net.Listener, net.Listener, error) {
|
||||
@@ -128,12 +130,12 @@ func initMultiplexer(addressConfiguration structure.AddressConfiguration) (net.L
|
||||
return httpListener, raftListener, nil
|
||||
}
|
||||
|
||||
func initWebsocket(ctx context.Context, connectionReadLimit int64, listener net.Listener, raftStore *store.Store) {
|
||||
func initWebsocket(connectionReadLimit int64, listener net.Listener, raftStore *store.Store) {
|
||||
etpConfig := etp.ServerConfig{
|
||||
InsecureSkipVerify: true,
|
||||
ConnectionReadLimit: connectionReadLimit,
|
||||
}
|
||||
etpServer := etp.NewServer(ctx, etpConfig)
|
||||
etpServer := etp.NewServer(context.Background(), etpConfig)
|
||||
subs.NewSocketEventHandler(etpServer, raftStore).SubscribeAll()
|
||||
|
||||
mux := http.NewServeMux()
|
||||
@@ -162,7 +164,7 @@ func initRaft(listener net.Listener, clusterCfg conf.ClusterConfiguration,
|
||||
return nil, nil
|
||||
}
|
||||
clusterClient := cluster.NewRaftClusterClient(r, declaration, func(address string) {
|
||||
raftStore.VisitState(func(s state.WritableState) {
|
||||
go raftStore.VisitState(func(s state.WritableState) {
|
||||
cfg := config.Get().(*conf.Configuration)
|
||||
addr, err := net.ResolveTCPAddr("tcp", address)
|
||||
if err != nil {
|
||||
@@ -173,7 +175,7 @@ func initRaft(listener net.Listener, clusterCfg conf.ClusterConfiguration,
|
||||
back := structure.BackendDeclaration{ModuleName: cfg.ModuleName, Address: addressConfiguration}
|
||||
log.WithMetadata(map[string]interface{}{"declaration": back}).
|
||||
Infof(codes.LeaderManualDeleteLeader, "manually delete disconnected leader's declaration")
|
||||
service.ClusterMeshService.HandleDeleteBackendDeclarationCommand(back, s)
|
||||
service.ClusterMesh.HandleDeleteBackendDeclarationCommand(back, s)
|
||||
})
|
||||
})
|
||||
holder.ClusterClient = clusterClient
|
||||
@@ -197,17 +199,45 @@ func initGrpc(bindAddress structure.AddressConfiguration, raftStore *store.Store
|
||||
backend.StartBackendGrpcServer(bindAddress, defaultService)
|
||||
}
|
||||
|
||||
func onShutdown(ctx context.Context, _ os.Signal) {
|
||||
defer close(shutdownChan)
|
||||
func gracefulShutdown() {
|
||||
const (
|
||||
gracefulTimeout = 10 * time.Second
|
||||
terminateTimeout = 11 * time.Second
|
||||
)
|
||||
|
||||
signalsCh := make(chan os.Signal, 1)
|
||||
signal.Notify(signalsCh, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT)
|
||||
sig := <-signalsCh
|
||||
log.Infof(0, "received signal '%s'", sig)
|
||||
|
||||
finishedCh := make(chan struct{})
|
||||
go func() {
|
||||
select {
|
||||
case <-time.After(terminateTimeout):
|
||||
log.Fatal(0, "exit timeout reached: terminating")
|
||||
case <-finishedCh:
|
||||
// ok
|
||||
case sig := <-signalsCh:
|
||||
log.Fatalf(0, "received duplicate exit signal '%s': terminating", sig)
|
||||
}
|
||||
}()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), gracefulTimeout)
|
||||
defer cancel()
|
||||
onShutdown(ctx)
|
||||
finishedCh <- struct{}{}
|
||||
log.Info(0, "application exited normally")
|
||||
}
|
||||
|
||||
func onShutdown(ctx context.Context) {
|
||||
backend.StopGrpcServer()
|
||||
holder.EtpServer.Close()
|
||||
|
||||
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")
|
||||
}
|
||||
holder.EtpServer.Close()
|
||||
|
||||
if err := holder.ClusterClient.Shutdown(); err != nil {
|
||||
log.Warnf(codes.RaftShutdownError, "raft shutdown err: %v", err)
|
||||
@@ -215,6 +245,10 @@ func onShutdown(ctx context.Context, _ os.Signal) {
|
||||
log.Info(codes.RaftShutdownInfo, "raft shutdown success")
|
||||
}
|
||||
|
||||
if err := model.DbClient.Close(); err != nil {
|
||||
log.Warnf(0, "database shutdown err: %v", err)
|
||||
}
|
||||
|
||||
_ = muxer.Close()
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
-- +goose Up
|
||||
CREATE TABLE version_config
|
||||
(
|
||||
id VARCHAR(255) NOT NULL PRIMARY KEY,
|
||||
config_id VARCHAR(255) NOT NULL,
|
||||
config_version INT4 NOT NULL,
|
||||
data JSONB NOT NULL DEFAULT '{}',
|
||||
created_at TIMESTAMP NOT NULL DEFAULT (now() at time zone 'utc')
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE version_config;
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE version_config
|
||||
ADD COLUMN IF NOT EXISTS created_at TIMESTAMP NOT NULL DEFAULT (now() at time zone 'utc');
|
||||
|
||||
-- +goose Down
|
||||
|
||||
|
||||
+5
-4
@@ -15,8 +15,9 @@ var (
|
||||
log.Fatal(stdcodes.InitializingDbError, err.Error())
|
||||
}),
|
||||
)
|
||||
ConfigRep ConfigRepository = &configRepPg{rxClient: DbClient}
|
||||
CommonConfigRep CommonConfigRepository = &commonConfigRepPg{rxClient: DbClient}
|
||||
SchemaRep SchemaRepository = &schemaRepPg{rxClient: DbClient}
|
||||
ModuleRep ModulesRepository = &modulesRepPg{rxClient: DbClient}
|
||||
ConfigRep ConfigRepository = &configRepPg{rxClient: DbClient}
|
||||
CommonConfigRep CommonConfigRepository = &commonConfigRepPg{rxClient: DbClient}
|
||||
SchemaRep SchemaRepository = &schemaRepPg{rxClient: DbClient}
|
||||
ModuleRep ModulesRepository = &modulesRepPg{rxClient: DbClient}
|
||||
VersionStoreRep VersionConfigRepository = &versionConfigRepPg{rxClient: DbClient}
|
||||
)
|
||||
@@ -1,4 +1,4 @@
|
||||
//nolint dupl
|
||||
//nolint: dupl
|
||||
package model
|
||||
|
||||
import (
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
//nolint dupl
|
||||
//nolint:dupl
|
||||
package model
|
||||
|
||||
import (
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
//nolint dupl
|
||||
//nolint:dupl
|
||||
package model
|
||||
|
||||
import (
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
//nolint dupl
|
||||
//nolint:dupl
|
||||
package model
|
||||
|
||||
import (
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"github.com/go-pg/pg/v9"
|
||||
"github.com/integration-system/isp-lib/v2/database"
|
||||
"isp-config-service/entity"
|
||||
)
|
||||
|
||||
type VersionConfigRepository interface {
|
||||
Snapshot() ([]entity.VersionConfig, error)
|
||||
Upsert(model entity.VersionConfig) (*entity.VersionConfig, error)
|
||||
Delete(identities string) (int, error)
|
||||
}
|
||||
|
||||
type versionConfigRepPg struct {
|
||||
rxClient *database.RxDbClient
|
||||
}
|
||||
|
||||
func (r *versionConfigRepPg) Snapshot() ([]entity.VersionConfig, error) {
|
||||
modules := make([]entity.VersionConfig, 0)
|
||||
err := r.rxClient.Visit(func(db *pg.DB) error {
|
||||
return db.Model(&modules).Select()
|
||||
})
|
||||
return modules, err
|
||||
}
|
||||
|
||||
func (r *versionConfigRepPg) Upsert(module entity.VersionConfig) (*entity.VersionConfig, error) {
|
||||
err := r.rxClient.Visit(func(db *pg.DB) error {
|
||||
_, err := db.Model(&module).
|
||||
OnConflict("(id) DO UPDATE").
|
||||
Returning("*").
|
||||
Insert()
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &module, err
|
||||
}
|
||||
|
||||
func (r *versionConfigRepPg) Delete(id string) (int, error) {
|
||||
var err error
|
||||
var res pg.Result
|
||||
err = r.rxClient.Visit(func(db *pg.DB) error {
|
||||
res, err = db.Model(&entity.VersionConfig{}).
|
||||
Where("id = ?", id).Delete()
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.RowsAffected(), err
|
||||
}
|
||||
+1
-1
@@ -7,7 +7,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/raft"
|
||||
raftboltdb "github.com/hashicorp/raft-boltdb"
|
||||
"github.com/hashicorp/raft-boltdb/v2"
|
||||
"github.com/integration-system/isp-log/adapter"
|
||||
"github.com/pkg/errors"
|
||||
"isp-config-service/codes"
|
||||
|
||||
@@ -6,7 +6,7 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
ClusterMeshService clusterMeshService
|
||||
ClusterMesh clusterMeshService
|
||||
)
|
||||
|
||||
type clusterMeshService struct{}
|
||||
@@ -14,15 +14,15 @@ type clusterMeshService struct{}
|
||||
func (clusterMeshService) HandleUpdateBackendDeclarationCommand(declaration structure.BackendDeclaration, state state.WritableState) {
|
||||
changed := state.WritableMesh().UpsertBackend(declaration)
|
||||
if changed {
|
||||
DiscoveryService.BroadcastModuleAddresses(declaration.ModuleName, state.Mesh())
|
||||
RoutesService.BroadcastRoutes(state.Mesh())
|
||||
Discovery.BroadcastModuleAddresses(declaration.ModuleName, state.Mesh())
|
||||
Routes.BroadcastRoutes(state.Mesh())
|
||||
}
|
||||
}
|
||||
|
||||
func (clusterMeshService) HandleDeleteBackendDeclarationCommand(declaration structure.BackendDeclaration, state state.WritableState) {
|
||||
deleted := state.WritableMesh().DeleteBackend(declaration)
|
||||
if deleted {
|
||||
DiscoveryService.BroadcastModuleAddresses(declaration.ModuleName, state.Mesh())
|
||||
RoutesService.BroadcastRoutes(state.Mesh())
|
||||
Discovery.BroadcastModuleAddresses(declaration.ModuleName, state.Mesh())
|
||||
Routes.BroadcastRoutes(state.Mesh())
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
CommonConfigService = commonConfigService{}
|
||||
CommonConfig = commonConfigService{}
|
||||
)
|
||||
|
||||
type commonConfigService struct{}
|
||||
@@ -72,7 +72,7 @@ func (s commonConfigService) HandleUpsertConfigCommand(
|
||||
}
|
||||
if !upsertConfig.Create {
|
||||
configsToBroadcast := state.Configs().FilterByCommonConfigs([]string{config.Id})
|
||||
ConfigService.BroadcastNewConfig(state, configsToBroadcast...)
|
||||
ConfigService.BroadcastActiveConfigs(state, configsToBroadcast...)
|
||||
}
|
||||
return cluster.NewResponse(config)
|
||||
}
|
||||
|
||||
+29
-15
@@ -23,8 +23,6 @@ var (
|
||||
ConfigService = configService{}
|
||||
)
|
||||
|
||||
const ConfigWatchersRoomSuffix = "_config"
|
||||
|
||||
type configService struct{}
|
||||
|
||||
type validationSchemaError struct {
|
||||
@@ -64,7 +62,7 @@ func (configService) CompileConfig(
|
||||
return mergeNestedMaps(configsToMerge...)
|
||||
}
|
||||
|
||||
func (configService) HandleActivateConfigCommand(
|
||||
func (cs configService) HandleActivateConfigCommand(
|
||||
activateConfig cluster.ActivateConfig, state state.WritableState) cluster.ResponseWithError {
|
||||
configs := state.Configs().GetByIds([]string{activateConfig.ConfigId})
|
||||
if len(configs) == 0 {
|
||||
@@ -83,7 +81,9 @@ func (configService) HandleActivateConfigCommand(
|
||||
}
|
||||
}
|
||||
}
|
||||
return cluster.NewResponse(affected[len(affected)-1])
|
||||
config = affected[len(affected)-1]
|
||||
cs.BroadcastActiveConfigs(state, config)
|
||||
return cluster.NewResponse(config)
|
||||
}
|
||||
|
||||
func (configService) HandleDeleteConfigsCommand(deleteConfigs cluster.DeleteConfigs, state state.WritableState) int {
|
||||
@@ -101,7 +101,8 @@ func (configService) HandleDeleteConfigsCommand(deleteConfigs cluster.DeleteConf
|
||||
return deleted
|
||||
}
|
||||
|
||||
func (cs configService) HandleUpsertConfigCommand(upsertConfig cluster.UpsertConfig, state state.WritableState) cluster.ResponseWithError {
|
||||
func (cs configService) HandleUpsertConfigCommand(upsertConfig cluster.UpsertConfig,
|
||||
state state.WritableState) cluster.ResponseWithError {
|
||||
config := upsertConfig.Config
|
||||
module := state.Modules().GetById(config.ModuleId)
|
||||
if module == nil {
|
||||
@@ -136,8 +137,13 @@ func (cs configService) HandleUpsertConfigCommand(upsertConfig cluster.UpsertCon
|
||||
if len(configs) == 0 {
|
||||
return cluster.NewResponseErrorf(codes2.NotFound, "config with id %s not found", config.Id)
|
||||
}
|
||||
config.CreatedAt = configs[0].CreatedAt
|
||||
oldCfg := configs[0]
|
||||
config.CreatedAt = oldCfg.CreatedAt
|
||||
config.Active = oldCfg.Active
|
||||
config.Version = oldCfg.Version + 1
|
||||
state.WritableConfigs().UpdateById(config)
|
||||
|
||||
ConfigHistory.SaveConfigVersion(upsertConfig.VersionId, oldCfg, state, upsertConfig.VersionCreateAt)
|
||||
}
|
||||
|
||||
if holder.ClusterClient.IsLeader() {
|
||||
@@ -149,7 +155,8 @@ func (cs configService) HandleUpsertConfigCommand(upsertConfig cluster.UpsertCon
|
||||
}).Errorf(codes.DatabaseOperationError, "upsert config: %v", err)
|
||||
}
|
||||
}
|
||||
cs.BroadcastNewConfig(state, config)
|
||||
|
||||
cs.BroadcastActiveConfigs(state, config)
|
||||
return cluster.NewResponse(domain.CreateUpdateConfigResponse{
|
||||
Config: &domain.ConfigModuleInfo{
|
||||
Config: config,
|
||||
@@ -159,12 +166,16 @@ func (cs configService) HandleUpsertConfigCommand(upsertConfig cluster.UpsertCon
|
||||
})
|
||||
}
|
||||
|
||||
func (cs configService) BroadcastNewConfig(state state.ReadonlyState, configs ...entity.Config) {
|
||||
func (cs configService) BroadcastActiveConfigs(state state.ReadonlyState, configs ...entity.Config) {
|
||||
for i := range configs {
|
||||
moduleID := configs[i].ModuleId
|
||||
cfg := &configs[i]
|
||||
if !cfg.Active {
|
||||
continue
|
||||
}
|
||||
moduleID := cfg.ModuleId
|
||||
module := state.Modules().GetById(moduleID)
|
||||
moduleName := module.Name
|
||||
room := moduleName + ConfigWatchersRoomSuffix
|
||||
room := Room.Module(moduleName)
|
||||
|
||||
compiledConfig, err := cs.GetCompiledConfig(moduleName, state)
|
||||
if err != nil {
|
||||
@@ -176,14 +187,17 @@ func (cs configService) BroadcastNewConfig(state state.ReadonlyState, configs ..
|
||||
go cs.broadcast(room, utils.ConfigError, []byte(err.Error()))
|
||||
continue
|
||||
}
|
||||
go cs.broadcast(room, utils.ConfigSendConfigWhenConnected, data)
|
||||
go cs.broadcast(room, utils.ConfigSendConfigChanged, data)
|
||||
}
|
||||
}
|
||||
|
||||
func (cs configService) broadcast(room, event string, data []byte) {
|
||||
err := holder.EtpServer.BroadcastToRoom(room, utils.ConfigSendConfigWhenConnected, data)
|
||||
if err != nil {
|
||||
log.Errorf(codes.ConfigServiceBroadcastConfigError, "broadcast %s err: %v", event, err)
|
||||
func (cs configService) broadcast(room, event string, body []byte) {
|
||||
conns := holder.EtpServer.Rooms().ToBroadcast(room)
|
||||
for _, conn := range conns {
|
||||
err := EmitConnWithTimeout(conn, event, body)
|
||||
if err != nil {
|
||||
log.Errorf(codes.ConfigServiceBroadcastConfigError, "broadcast '%s' to %s: %v", event, conn.RemoteAddr(), err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"isp-config-service/entity"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestConfigService_validateSchema(t *testing.T) {
|
||||
var (
|
||||
a = assert.New(t)
|
||||
|
||||
schemaDesc = []byte(`{"schema":{"properties":{"configuration":{"required":["address","token"],"properties":{"address":{"type":"string","title":"Адрес"},"token":{"type":"string","title":"Токен"}},"additionalProperties":false,"type":"object"}},"additionalProperties":false,"type":"object","title":"Remote config"},"title":"module_name"}`)
|
||||
validData = map[string]interface{}{"configuration": map[string]interface{}{"address": "127.0.0.1", "token": "token"}}
|
||||
invalidValue = map[string]interface{}{"configuration": map[string]interface{}{"address": 127001, "token": "token"}}
|
||||
invalidName = map[string]interface{}{"config": map[string]interface{}{"test": "127.0.0.1", "token": "token"}}
|
||||
|
||||
schema entity.ConfigSchema
|
||||
valid bool
|
||||
err error
|
||||
)
|
||||
|
||||
a.NoError(json.Unmarshal(schemaDesc, &schema))
|
||||
|
||||
valid, err = ConfigService.validateSchema(schema, validData)
|
||||
a.NoError(err)
|
||||
a.True(valid)
|
||||
|
||||
valid, err = ConfigService.validateSchema(schema, invalidValue)
|
||||
a.Error(err)
|
||||
a.False(valid)
|
||||
|
||||
valid, err = ConfigService.validateSchema(schema, invalidName)
|
||||
a.Error(err)
|
||||
a.False(valid)
|
||||
}
|
||||
+69
-49
@@ -1,28 +1,27 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/cenkalti/backoff/v4"
|
||||
etp "github.com/integration-system/isp-etp-go/v2"
|
||||
"github.com/integration-system/isp-lib/v2/structure"
|
||||
"github.com/integration-system/isp-lib/v2/utils"
|
||||
log "github.com/integration-system/isp-log"
|
||||
"isp-config-service/cluster"
|
||||
"isp-config-service/codes"
|
||||
"isp-config-service/holder"
|
||||
"isp-config-service/store/state"
|
||||
)
|
||||
|
||||
const (
|
||||
messagesBackoffInterval = 100 * time.Millisecond
|
||||
messagesBackoffMaxRetries = 3
|
||||
AllModules = "*"
|
||||
)
|
||||
|
||||
var (
|
||||
DiscoveryService = NewDiscoveryService()
|
||||
Discovery = &discoveryService{
|
||||
subs: make(map[string][]string),
|
||||
}
|
||||
)
|
||||
|
||||
type discoveryService struct {
|
||||
@@ -33,8 +32,8 @@ type discoveryService struct {
|
||||
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...)
|
||||
if rooms, ok := ds.subs[connID]; ok {
|
||||
holder.EtpServer.Rooms().LeaveByConnId(connID, rooms...)
|
||||
delete(ds.subs, connID)
|
||||
}
|
||||
}
|
||||
@@ -46,70 +45,91 @@ func (ds *discoveryService) Subscribe(conn etp.Conn, modules []string, mesh stat
|
||||
ds.lock.Lock()
|
||||
defer ds.lock.Unlock()
|
||||
eventsAddresses := make([][]structure.AddressConfiguration, 0, len(modules))
|
||||
events := make([]string, 0, len(modules))
|
||||
rooms := make([]string, 0, len(modules))
|
||||
for _, module := range modules {
|
||||
event := utils.ModuleConnected(module)
|
||||
room := Room.AddressListener(module)
|
||||
addressList := mesh.GetModuleAddresses(module)
|
||||
eventsAddresses = append(eventsAddresses, addressList)
|
||||
events = append(events, event)
|
||||
rooms = append(rooms, room)
|
||||
}
|
||||
ds.subs[conn.ID()] = events
|
||||
holder.EtpServer.Rooms().Join(conn, events...)
|
||||
ds.subs[conn.ID()] = rooms
|
||||
holder.EtpServer.Rooms().Join(conn, rooms...)
|
||||
|
||||
go func(events []string, eventsAddresses [][]structure.AddressConfiguration, conn etp.Conn) {
|
||||
for i := range events {
|
||||
event := events[i]
|
||||
addressList := eventsAddresses[i]
|
||||
err := ds.sendAddrList(conn, event, addressList)
|
||||
body, err := json.Marshal(addressList)
|
||||
if err != nil {
|
||||
log.Errorf(codes.DiscoveryServiceSendModulesError, "send module connected %v", err)
|
||||
panic(err)
|
||||
}
|
||||
err = EmitConnWithTimeout(conn, event, body)
|
||||
if err != nil {
|
||||
log.Errorf(codes.DiscoveryServiceSendModulesError, "send module connected to %s: %v", conn.RemoteAddr(), err)
|
||||
}
|
||||
}
|
||||
}(events, eventsAddresses, conn)
|
||||
}(rooms, eventsAddresses, conn)
|
||||
}
|
||||
|
||||
func (ds *discoveryService) BroadcastModuleAddresses(moduleName string, mesh state.ReadonlyMesh) {
|
||||
ds.lock.RLock()
|
||||
defer ds.lock.RUnlock()
|
||||
room := Room.AddressListener(moduleName)
|
||||
event := utils.ModuleConnected(moduleName)
|
||||
addressList := mesh.GetModuleAddresses(moduleName)
|
||||
go func(room, event string, addressList []structure.AddressConfiguration) {
|
||||
err := ds.broadcastAddrList(room, event, addressList)
|
||||
if err != nil {
|
||||
log.Errorf(codes.DiscoveryServiceSendModulesError, "broadcast module connected %v", err)
|
||||
go ds.broadcastModuleAddrList(room, event, addressList)
|
||||
}
|
||||
|
||||
func (ds *discoveryService) BroadcastEvent(event cluster.BroadcastEvent) {
|
||||
eventName := event.Event
|
||||
payload := make([]byte, len(event.Payload))
|
||||
copy(payload, event.Payload) // TODO а тут точно нужно копирование ?
|
||||
|
||||
if len(event.ModuleNames) == 1 && event.ModuleNames[0] == AllModules {
|
||||
go func() {
|
||||
conns := holder.EtpServer.Rooms().AllConns()
|
||||
for _, conn := range conns {
|
||||
err := EmitConnWithTimeout(conn, eventName, payload)
|
||||
if err != nil {
|
||||
log.WithMetadata(map[string]interface{}{
|
||||
"eventName": eventName,
|
||||
"remote_address": conn.RemoteAddr(),
|
||||
}).Errorf(codes.DiscoveryServiceSendModulesError, "broadcast event to all modules: %v", err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
return
|
||||
}
|
||||
|
||||
rooms := make([]string, 0, len(event.ModuleNames))
|
||||
for _, moduleName := range event.ModuleNames {
|
||||
room := Room.Module(moduleName)
|
||||
rooms = append(rooms, room)
|
||||
}
|
||||
go func(rooms []string) {
|
||||
conns := holder.EtpServer.Rooms().ToBroadcast(rooms...)
|
||||
for _, conn := range conns {
|
||||
err := EmitConnWithTimeout(conn, eventName, payload)
|
||||
if err != nil {
|
||||
log.WithMetadata(map[string]interface{}{
|
||||
"eventName": eventName,
|
||||
"remote_address": conn.RemoteAddr(),
|
||||
}).Errorf(codes.DiscoveryServiceSendModulesError, "broadcast event: %v", err)
|
||||
}
|
||||
}
|
||||
}(event, event, addressList)
|
||||
}(rooms)
|
||||
}
|
||||
|
||||
func (ds *discoveryService) broadcastAddrList(room string, event string, addressList []structure.AddressConfiguration) error {
|
||||
bytes, err := json.Marshal(addressList)
|
||||
func (ds *discoveryService) broadcastModuleAddrList(room string, event string, addressList []structure.AddressConfiguration) {
|
||||
body, err := json.Marshal(addressList)
|
||||
if err != nil {
|
||||
return err
|
||||
panic(err)
|
||||
}
|
||||
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 {
|
||||
bytes, err := json.Marshal(addressList)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
bf := backoff.WithMaxRetries(backoff.NewConstantBackOff(messagesBackoffInterval), messagesBackoffMaxRetries)
|
||||
err = backoff.Retry(func() error {
|
||||
return conn.Emit(context.Background(), event, bytes)
|
||||
}, bf)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewDiscoveryService() *discoveryService {
|
||||
return &discoveryService{
|
||||
subs: make(map[string][]string),
|
||||
conns := holder.EtpServer.Rooms().ToBroadcast(room)
|
||||
for _, conn := range conns {
|
||||
err := EmitConnWithTimeout(conn, event, body)
|
||||
if err != nil {
|
||||
log.Errorf(codes.DiscoveryServiceSendModulesError, "broadcast module connected to %s: %v", conn.RemoteAddr(), err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,7 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
ModuleRegistryService = moduleRegistryService{}
|
||||
ModuleRegistry = moduleRegistryService{}
|
||||
)
|
||||
|
||||
type moduleRegistryService struct{}
|
||||
@@ -104,24 +104,38 @@ func (moduleRegistryService) HandleDeleteModulesCommand(deleteModules cluster.De
|
||||
return len(deletedModules)
|
||||
}
|
||||
|
||||
func (moduleRegistryService) ValidateConfig(config entity.Config, state state.ReadonlyState) bool {
|
||||
schemas := state.Schemas().GetByModuleIds([]string{config.ModuleId})
|
||||
valid := false
|
||||
|
||||
for _, s := range schemas {
|
||||
dataForValidate := ConfigService.CompileConfig(config.Data, state, config.CommonConfigs...)
|
||||
valid, _ = ConfigService.validateSchema(s, dataForValidate)
|
||||
}
|
||||
|
||||
return valid
|
||||
}
|
||||
|
||||
//nolint:funlen
|
||||
func (moduleRegistryService) GetAggregatedModuleInfo(state state.ReadonlyState) []domain.ModuleInfo {
|
||||
modules := state.Modules().GetAll()
|
||||
modulesLen := len(modules)
|
||||
result := make([]domain.ModuleInfo, 0, modulesLen)
|
||||
resMap := make(map[string]domain.ModuleInfo, modulesLen)
|
||||
nameIdMap := make(map[string]string)
|
||||
idList := make([]string, modulesLen)
|
||||
|
||||
for i, module := range modules {
|
||||
idList[i] = module.Id
|
||||
active := state.Mesh().BackendExist(structure.BackendDeclaration{ModuleName: module.Name})
|
||||
info := domain.ModuleInfo{
|
||||
Id: module.Id,
|
||||
Name: module.Name,
|
||||
Active: active,
|
||||
CreatedAt: module.CreatedAt,
|
||||
LastConnectedAt: module.LastConnectedAt,
|
||||
LastDisconnectedAt: module.LastDisconnectedAt,
|
||||
}
|
||||
resMap[module.Id] = info
|
||||
nameIdMap[module.Name] = module.Id
|
||||
}
|
||||
|
||||
configs := state.Configs().GetByModuleIds(idList)
|
||||
@@ -131,9 +145,9 @@ func (moduleRegistryService) GetAggregatedModuleInfo(state state.ReadonlyState)
|
||||
Config: configs[i],
|
||||
Valid: false,
|
||||
})
|
||||
|
||||
resMap[configs[i].ModuleId] = info
|
||||
}
|
||||
|
||||
schemas := state.Schemas().GetByModuleIds(idList)
|
||||
for _, s := range schemas {
|
||||
info := resMap[s.ModuleId]
|
||||
@@ -153,23 +167,41 @@ func (moduleRegistryService) GetAggregatedModuleInfo(state state.ReadonlyState)
|
||||
backends := state.Mesh().GetBackends(info.Name)
|
||||
conns := make([]domain.Connection, 0, len(backends))
|
||||
|
||||
if len(backends) > 0 {
|
||||
back := backends[0]
|
||||
requiredModules := make([]domain.ModuleDependency, 0, len(back.RequiredModules))
|
||||
for _, dep := range back.RequiredModules {
|
||||
requiredModules = append(requiredModules, domain.ModuleDependency{
|
||||
Name: dep.Name,
|
||||
Id: nameIdMap[dep.Name],
|
||||
Required: dep.Required,
|
||||
})
|
||||
}
|
||||
info.RequiredModules = requiredModules
|
||||
}
|
||||
|
||||
for _, back := range backends {
|
||||
con := domain.Connection{
|
||||
Version: back.Version,
|
||||
LibVersion: back.LibVersion,
|
||||
Address: back.Address,
|
||||
Endpoints: back.Endpoints,
|
||||
Endpoints: make([]structure.EndpointDescriptor, len(back.Endpoints)),
|
||||
}
|
||||
copy(con.Endpoints, back.Endpoints)
|
||||
sort.Slice(con.Endpoints, func(i, j int) bool {
|
||||
return con.Endpoints[i].Path < con.Endpoints[j].Path
|
||||
})
|
||||
con.EstablishedAt = info.LastConnectedAt
|
||||
conns = append(conns, con)
|
||||
}
|
||||
sort.Slice(info.Configs, func(i, j int) bool {
|
||||
return info.Configs[i].Version < info.Configs[j].Version
|
||||
})
|
||||
sort.Slice(conns, func(i, j int) bool {
|
||||
return conns[i].EstablishedAt.Before(conns[j].EstablishedAt)
|
||||
})
|
||||
info.Status = conns
|
||||
info.Active = len(conns) > 0
|
||||
result = append(result, info)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
etp "github.com/integration-system/isp-etp-go/v2"
|
||||
"github.com/integration-system/isp-lib/v2/utils"
|
||||
)
|
||||
|
||||
const (
|
||||
configWatchersRoomSuffix = "_config"
|
||||
routesSubscribersRoom = "__routesSubscribers"
|
||||
)
|
||||
|
||||
const wsWriteTimeout = time.Second
|
||||
|
||||
var (
|
||||
Room = roomService{}
|
||||
)
|
||||
|
||||
type roomService struct{}
|
||||
|
||||
func (s roomService) Module(moduleName string) string {
|
||||
return moduleName + configWatchersRoomSuffix
|
||||
}
|
||||
|
||||
func (s roomService) RoutesSubscribers() string {
|
||||
return routesSubscribersRoom
|
||||
}
|
||||
|
||||
func (s roomService) AddressListener(moduleName string) string {
|
||||
return utils.ModuleConnected(moduleName)
|
||||
}
|
||||
|
||||
func EmitConnWithTimeout(conn etp.Conn, event string, body []byte) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), wsWriteTimeout)
|
||||
defer cancel()
|
||||
return conn.Emit(ctx, event, body)
|
||||
}
|
||||
+22
-43
@@ -1,12 +1,9 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/cenkalti/backoff/v4"
|
||||
etp "github.com/integration-system/isp-etp-go/v2"
|
||||
"github.com/integration-system/isp-lib/v2/structure"
|
||||
"github.com/integration-system/isp-lib/v2/utils"
|
||||
log "github.com/integration-system/isp-log"
|
||||
"isp-config-service/codes"
|
||||
@@ -14,62 +11,44 @@ import (
|
||||
"isp-config-service/store/state"
|
||||
)
|
||||
|
||||
const (
|
||||
RoutesSubscribersRoom = "__routesSubscribers"
|
||||
)
|
||||
|
||||
var RoutesService routesService
|
||||
var Routes routesService
|
||||
|
||||
type routesService struct{}
|
||||
|
||||
func (rs *routesService) HandleDisconnect(connID string) {
|
||||
holder.EtpServer.Rooms().LeaveByConnId(connID, RoutesSubscribersRoom)
|
||||
holder.EtpServer.Rooms().LeaveByConnId(connID, Room.RoutesSubscribers())
|
||||
}
|
||||
|
||||
func (rs *routesService) SubscribeRoutes(conn etp.Conn, mesh state.ReadonlyMesh) {
|
||||
holder.EtpServer.Rooms().Join(conn, RoutesSubscribersRoom)
|
||||
holder.EtpServer.Rooms().Join(conn, Room.RoutesSubscribers())
|
||||
routes := mesh.GetRoutes()
|
||||
go func(conn etp.Conn, routes structure.RoutingConfig) {
|
||||
err := rs.sendRoutes(conn, utils.ConfigSendRoutesWhenConnected, routes)
|
||||
body, err := json.Marshal(routes)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
go func() {
|
||||
err := EmitConnWithTimeout(conn, utils.ConfigSendRoutesWhenConnected, body)
|
||||
if err != nil {
|
||||
log.Errorf(codes.RoutesServiceSendRoutesError, "send routes %v", err)
|
||||
log.Errorf(codes.RoutesServiceSendRoutesError, "send routes to %s: %v", conn.RemoteAddr(), err)
|
||||
}
|
||||
}(conn, routes)
|
||||
}()
|
||||
}
|
||||
|
||||
func (rs *routesService) BroadcastRoutes(mesh state.ReadonlyMesh) {
|
||||
routes := mesh.GetRoutes()
|
||||
go func(routes structure.RoutingConfig) {
|
||||
err := rs.broadcastRoutes(utils.ConfigSendRoutesChanged, routes)
|
||||
if err != nil {
|
||||
log.Errorf(codes.RoutesServiceSendRoutesError, "broadcast routes %v", err)
|
||||
}
|
||||
}(routes)
|
||||
}
|
||||
|
||||
func (rs *routesService) broadcastRoutes(event string, routes structure.RoutingConfig) error {
|
||||
bytes, err := json.Marshal(routes)
|
||||
body, err := json.Marshal(routes)
|
||||
if err != nil {
|
||||
return err
|
||||
panic(err)
|
||||
}
|
||||
err = holder.EtpServer.BroadcastToRoom(RoutesSubscribersRoom, event, bytes)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (rs *routesService) sendRoutes(conn etp.Conn, event string, routes structure.RoutingConfig) error {
|
||||
if bytes, err := json.Marshal(routes); err != nil {
|
||||
return err
|
||||
} else {
|
||||
bf := backoff.WithMaxRetries(backoff.NewConstantBackOff(messagesBackoffInterval), messagesBackoffMaxRetries)
|
||||
err := backoff.Retry(func() error {
|
||||
return conn.Emit(context.Background(), event, bytes)
|
||||
}, bf)
|
||||
if err != nil {
|
||||
return err
|
||||
go func() {
|
||||
conns := holder.EtpServer.Rooms().ToBroadcast(Room.RoutesSubscribers())
|
||||
for _, conn := range conns {
|
||||
err := EmitConnWithTimeout(conn, utils.ConfigSendRoutesChanged, body)
|
||||
if err != nil {
|
||||
log.Errorf(codes.RoutesServiceSendRoutesError, "broadcast routes to %s: %v", conn.RemoteAddr(), err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}()
|
||||
}
|
||||
+1
-1
@@ -11,7 +11,7 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
SchemaService schemaService
|
||||
Schema schemaService
|
||||
)
|
||||
|
||||
type schemaService struct{}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
log "github.com/integration-system/isp-log"
|
||||
"isp-config-service/cluster"
|
||||
"isp-config-service/codes"
|
||||
"isp-config-service/domain"
|
||||
"isp-config-service/entity"
|
||||
"isp-config-service/holder"
|
||||
"isp-config-service/model"
|
||||
"isp-config-service/store/state"
|
||||
)
|
||||
|
||||
var (
|
||||
ConfigHistory = configHistoryService{}
|
||||
)
|
||||
|
||||
type configHistoryService struct{}
|
||||
|
||||
func (configHistoryService) HandleDeleteVersionConfigCommand(cfg cluster.Identity,
|
||||
state state.WritableState) cluster.ResponseWithError {
|
||||
state.WriteableVersionConfigStore().Delete(cfg.Id)
|
||||
var (
|
||||
deleted int
|
||||
err error
|
||||
)
|
||||
if holder.ClusterClient.IsLeader() {
|
||||
// TODO handle db errors
|
||||
deleted, err = model.VersionStoreRep.Delete(cfg.Id)
|
||||
if err != nil {
|
||||
log.WithMetadata(map[string]interface{}{
|
||||
"versionConfigId": cfg.Id,
|
||||
}).Errorf(codes.DatabaseOperationError, "delete configs: %v", err)
|
||||
}
|
||||
}
|
||||
return cluster.NewResponse(domain.DeleteResponse{Deleted: deleted})
|
||||
}
|
||||
|
||||
func (configHistoryService) GetAllVersionConfigById(id string, state state.ReadonlyState) []entity.VersionConfig {
|
||||
return state.VersionConfig().GetByConfigId(id)
|
||||
}
|
||||
|
||||
func (s configHistoryService) SaveConfigVersion(id string, oldConfig entity.Config,
|
||||
state state.WritableState, createdAt time.Time) {
|
||||
cfg := entity.VersionConfig{
|
||||
Id: id,
|
||||
ConfigVersion: oldConfig.Version,
|
||||
ConfigId: oldConfig.Id,
|
||||
Data: oldConfig.Data,
|
||||
CreatedAt: createdAt,
|
||||
}
|
||||
removedVersionId := state.WriteableVersionConfigStore().Update(cfg)
|
||||
if holder.ClusterClient.IsLeader() {
|
||||
s.updateDB(cfg, removedVersionId)
|
||||
}
|
||||
}
|
||||
|
||||
func (configHistoryService) updateDB(cfg entity.VersionConfig, removedId string) {
|
||||
_, err := model.VersionStoreRep.Upsert(cfg)
|
||||
if err != nil {
|
||||
log.WithMetadata(map[string]interface{}{
|
||||
"version_config": cfg,
|
||||
}).Errorf(codes.DatabaseOperationError, "upsert version config: %v", err)
|
||||
}
|
||||
if removedId != "" {
|
||||
_, err := model.VersionStoreRep.Delete(removedId)
|
||||
if err != nil {
|
||||
log.WithMetadata(map[string]interface{}{
|
||||
"version_config_id": removedId,
|
||||
}).Errorf(codes.DatabaseOperationError, "delete version config: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
+32
-8
@@ -1,6 +1,8 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/integration-system/isp-lib/v2/structure"
|
||||
"github.com/pkg/errors"
|
||||
"isp-config-service/cluster"
|
||||
@@ -15,7 +17,7 @@ func (s *Store) applyUpdateBackendDeclarationCommand(data []byte) (interface{},
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "unmarshal structure.BackendDeclaration")
|
||||
}
|
||||
service.ClusterMeshService.HandleUpdateBackendDeclarationCommand(declaration, s.state)
|
||||
service.ClusterMesh.HandleUpdateBackendDeclarationCommand(declaration, s.state)
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
@@ -25,7 +27,7 @@ func (s *Store) applyDeleteBackendDeclarationCommand(data []byte) (interface{},
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "unmarshal structure.BackendDeclaration")
|
||||
}
|
||||
service.ClusterMeshService.HandleDeleteBackendDeclarationCommand(declaration, s.state)
|
||||
service.ClusterMesh.HandleDeleteBackendDeclarationCommand(declaration, s.state)
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
@@ -35,7 +37,7 @@ func (s *Store) applyUpdateConfigSchemaCommand(data []byte) (interface{}, error)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "unmarshal entity.ConfigSchema")
|
||||
}
|
||||
err = service.SchemaService.HandleUpdateConfigSchemaCommand(schema, s.state)
|
||||
err = service.Schema.HandleUpdateConfigSchemaCommand(schema, s.state)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "update config schema")
|
||||
}
|
||||
@@ -48,7 +50,7 @@ func (s *Store) applyModuleConnectedCommand(data []byte) (interface{}, error) {
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "unmarshal entity.Module")
|
||||
}
|
||||
service.ModuleRegistryService.HandleModuleConnectedCommand(module, s.state)
|
||||
service.ModuleRegistry.HandleModuleConnectedCommand(module, s.state)
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
@@ -58,7 +60,7 @@ func (s *Store) applyModuleDisconnectedCommand(data []byte) (interface{}, error)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "unmarshal entity.Module")
|
||||
}
|
||||
service.ModuleRegistryService.HandleModuleDisconnectedCommand(module, s.state)
|
||||
service.ModuleRegistry.HandleModuleDisconnectedCommand(module, s.state)
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
@@ -68,7 +70,7 @@ func (s *Store) applyDeleteModulesCommand(data []byte) (interface{}, error) {
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "unmarshal cluster.DeleteModules")
|
||||
}
|
||||
deleted := service.ModuleRegistryService.HandleDeleteModulesCommand(deleteModules, s.state)
|
||||
deleted := service.ModuleRegistry.HandleDeleteModulesCommand(deleteModules, s.state)
|
||||
return domain.DeleteResponse{Deleted: deleted}, nil
|
||||
}
|
||||
|
||||
@@ -108,7 +110,7 @@ func (s *Store) applyDeleteCommonConfigsCommand(data []byte) (interface{}, error
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "unmarshal cluster.DeleteCommonConfig")
|
||||
}
|
||||
response := service.CommonConfigService.HandleDeleteConfigsCommand(deleteConfigs, s.state)
|
||||
response := service.CommonConfig.HandleDeleteConfigsCommand(deleteConfigs, s.state)
|
||||
return response, nil
|
||||
}
|
||||
|
||||
@@ -118,6 +120,28 @@ func (s *Store) applyUpsertCommonConfigCommand(data []byte) (interface{}, error)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "unmarshal cluster.UpsertCommonConfig")
|
||||
}
|
||||
response := service.CommonConfigService.HandleUpsertConfigCommand(config, s.state)
|
||||
response := service.CommonConfig.HandleUpsertConfigCommand(config, s.state)
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func (s *Store) applyBroadcastEventCommand(data []byte) (interface{}, error) {
|
||||
event := cluster.BroadcastEvent{}
|
||||
err := json.Unmarshal(data, &event)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "unmarshal cluster.BroadcastEvent")
|
||||
}
|
||||
if event.PerformUntil.After(time.Now().UTC()) {
|
||||
service.Discovery.BroadcastEvent(event)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *Store) applyDeleteVersionConfigCommand(data []byte) (interface{}, error) {
|
||||
cfg := cluster.Identity{}
|
||||
err := json.Unmarshal(data, &cfg)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "unmarshal cluster.Identity")
|
||||
}
|
||||
response := service.ConfigHistory.HandleDeleteVersionConfigCommand(cfg, s.state)
|
||||
return response, nil
|
||||
}
|
||||
+6
-1
@@ -24,6 +24,11 @@ func NewStateFromRepository() (*state.State, error) {
|
||||
return nil, errors.WithMessage(err, "load common configs")
|
||||
}
|
||||
|
||||
st := state.NewStateFromSnapshot(configs, schemas, modules, commonConfigs)
|
||||
versionStore, err := model.VersionStoreRep.Snapshot()
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "load version store")
|
||||
}
|
||||
|
||||
st := state.NewStateFromSnapshot(configs, schemas, modules, commonConfigs, versionStore)
|
||||
return st, nil
|
||||
}
|
||||
+21
-45
@@ -11,8 +11,6 @@ type WriteableMesh interface {
|
||||
}
|
||||
|
||||
type ReadonlyMesh interface {
|
||||
CheckBackendChanged(backend structure.BackendDeclaration) (changed bool)
|
||||
BackendExist(backend structure.BackendDeclaration) (exist bool)
|
||||
GetModuleAddresses(moduleName string) []structure.AddressConfiguration
|
||||
GetBackends(module string) []structure.BackendDeclaration
|
||||
GetRoutes() structure.RoutingConfig
|
||||
@@ -25,14 +23,8 @@ type Mesh struct {
|
||||
ModulesMap map[string]NodesMap
|
||||
}
|
||||
|
||||
func (m Mesh) BackendExist(backend structure.BackendDeclaration) (exist bool) {
|
||||
address := backend.Address.GetAddress()
|
||||
if nodes, ok := m.ModulesMap[backend.ModuleName]; ok {
|
||||
if _, ok := nodes[address]; ok {
|
||||
exist = true
|
||||
}
|
||||
}
|
||||
return
|
||||
func NewMesh() *Mesh {
|
||||
return &Mesh{ModulesMap: make(map[string]NodesMap)}
|
||||
}
|
||||
|
||||
func (m Mesh) GetBackends(module string) []structure.BackendDeclaration {
|
||||
@@ -57,47 +49,35 @@ func (m Mesh) GetModuleAddresses(moduleName string) []structure.AddressConfigura
|
||||
|
||||
func (m Mesh) GetRoutes() structure.RoutingConfig {
|
||||
routes := structure.RoutingConfig{}
|
||||
for _, node := range m.ModulesMap {
|
||||
for _, backend := range node {
|
||||
for _, nodes := range m.ModulesMap {
|
||||
for _, backend := range nodes {
|
||||
routes = append(routes, backend)
|
||||
}
|
||||
}
|
||||
return routes
|
||||
}
|
||||
|
||||
func (m Mesh) CheckBackendChanged(backend structure.BackendDeclaration) (changed bool) {
|
||||
func (m *Mesh) UpsertBackend(backend structure.BackendDeclaration) bool {
|
||||
address := backend.Address.GetAddress()
|
||||
if nodes, ok := m.ModulesMap[backend.ModuleName]; ok {
|
||||
if oldBackend, ok := nodes[address]; ok {
|
||||
if oldBackend.Version != backend.Version || !oldBackend.IsPathsEqual(backend.Endpoints) || oldBackend.LibVersion != backend.LibVersion {
|
||||
changed = true
|
||||
}
|
||||
} else {
|
||||
changed = true
|
||||
}
|
||||
} else {
|
||||
changed = true
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (m *Mesh) UpsertBackend(backend structure.BackendDeclaration) (changed bool) {
|
||||
address := backend.Address.GetAddress()
|
||||
if nodes, ok := m.ModulesMap[backend.ModuleName]; ok {
|
||||
if oldBackend, ok := nodes[address]; ok {
|
||||
if oldBackend.Version != backend.Version || !oldBackend.IsPathsEqual(backend.Endpoints) || oldBackend.LibVersion != backend.LibVersion {
|
||||
nodes[address] = backend
|
||||
changed = true
|
||||
}
|
||||
} else {
|
||||
nodes[address] = backend
|
||||
changed = true
|
||||
}
|
||||
} else {
|
||||
nodes, ok := m.ModulesMap[backend.ModuleName]
|
||||
if !ok {
|
||||
m.ModulesMap[backend.ModuleName] = NodesMap{address: backend}
|
||||
changed = true
|
||||
return true
|
||||
}
|
||||
return
|
||||
|
||||
old, ok := nodes[address]
|
||||
if !ok {
|
||||
nodes[address] = backend
|
||||
return true
|
||||
}
|
||||
|
||||
if old.Version != backend.Version || !old.IsPathsEqual(backend.Endpoints) || old.LibVersion != backend.LibVersion {
|
||||
nodes[address] = backend
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func (m *Mesh) DeleteBackend(backend structure.BackendDeclaration) (deleted bool) {
|
||||
@@ -113,7 +93,3 @@ func (m *Mesh) DeleteBackend(backend structure.BackendDeclaration) (deleted bool
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func NewMesh() *Mesh {
|
||||
return &Mesh{ModulesMap: make(map[string]NodesMap)}
|
||||
}
|
||||
+14
-1
@@ -10,6 +10,7 @@ type State struct {
|
||||
SchemasStore *SchemaStore
|
||||
ModulesStore *ModuleStore
|
||||
CommonConfigsStore *CommonConfigStore
|
||||
VersionConfigStore *VersionConfigStore
|
||||
}
|
||||
|
||||
func (s State) Mesh() ReadonlyMesh {
|
||||
@@ -32,6 +33,10 @@ func (s State) CommonConfigs() ReadonlyCommonConfigStore {
|
||||
return s.CommonConfigsStore
|
||||
}
|
||||
|
||||
func (s State) VersionConfig() ReadonlyVersionConfigStore {
|
||||
return s.VersionConfigStore
|
||||
}
|
||||
|
||||
func (s *State) WritableMesh() WriteableMesh {
|
||||
return s.MeshStore
|
||||
}
|
||||
@@ -52,6 +57,10 @@ func (s *State) WritableCommonConfigs() WriteableCommonConfigStore {
|
||||
return s.CommonConfigsStore
|
||||
}
|
||||
|
||||
func (s *State) WriteableVersionConfigStore() WriteableVersionConfigStore {
|
||||
return s.VersionConfigStore
|
||||
}
|
||||
|
||||
type WritableState interface {
|
||||
ReadonlyState
|
||||
WritableMesh() WriteableMesh
|
||||
@@ -59,6 +68,7 @@ type WritableState interface {
|
||||
WritableSchemas() WriteableSchemaStore
|
||||
WritableModules() WriteableModuleStore
|
||||
WritableCommonConfigs() WriteableCommonConfigStore
|
||||
WriteableVersionConfigStore() WriteableVersionConfigStore
|
||||
}
|
||||
|
||||
type ReadonlyState interface {
|
||||
@@ -67,6 +77,7 @@ type ReadonlyState interface {
|
||||
Schemas() ReadonlySchemaStore
|
||||
Modules() ReadonlyModuleStore
|
||||
CommonConfigs() ReadonlyCommonConfigStore
|
||||
VersionConfig() ReadonlyVersionConfigStore
|
||||
}
|
||||
|
||||
func NewState() *State {
|
||||
@@ -76,16 +87,18 @@ func NewState() *State {
|
||||
SchemasStore: NewSchemaStore(),
|
||||
ModulesStore: NewModuleStore(),
|
||||
CommonConfigsStore: NewCommonConfigStore(),
|
||||
VersionConfigStore: NewVersionConfigStore(),
|
||||
}
|
||||
}
|
||||
|
||||
func NewStateFromSnapshot(configs []entity.Config, schemas []entity.ConfigSchema,
|
||||
modules []entity.Module, commConfigs []entity.CommonConfig) *State {
|
||||
modules []entity.Module, commConfigs []entity.CommonConfig, versionStore []entity.VersionConfig) *State {
|
||||
return &State{
|
||||
MeshStore: NewMesh(),
|
||||
ConfigsStore: &ConfigStore{Configs: configs},
|
||||
SchemasStore: &SchemaStore{Schemas: schemas},
|
||||
ModulesStore: &ModuleStore{Modules: modules},
|
||||
CommonConfigsStore: &CommonConfigStore{Configs: commConfigs},
|
||||
VersionConfigStore: NewVersionConfigStoreFromSnapshot(versionStore),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package state
|
||||
|
||||
import (
|
||||
"github.com/integration-system/isp-lib/v2/config"
|
||||
"isp-config-service/conf"
|
||||
"isp-config-service/entity"
|
||||
)
|
||||
|
||||
const DefaultVersionCount = 15
|
||||
|
||||
type WriteableVersionConfigStore interface {
|
||||
ReadonlyVersionConfigStore
|
||||
Update(config entity.VersionConfig) (removedId string)
|
||||
Delete(id string)
|
||||
}
|
||||
|
||||
type ReadonlyVersionConfigStore interface {
|
||||
GetByConfigId(id string) []entity.VersionConfig
|
||||
}
|
||||
|
||||
type VersionConfigStore struct {
|
||||
VersionByConfigId map[string][]entity.VersionConfig
|
||||
}
|
||||
|
||||
func (s *VersionConfigStore) Update(req entity.VersionConfig) string {
|
||||
limit := config.Get().(*conf.Configuration).VersionConfigCount
|
||||
if limit <= 0 {
|
||||
limit = DefaultVersionCount
|
||||
}
|
||||
var removedId string
|
||||
store, found := s.VersionByConfigId[req.ConfigId]
|
||||
if found {
|
||||
if len(store) >= limit {
|
||||
removedId = store[0].Id
|
||||
store = append(store[1:], req)
|
||||
} else {
|
||||
store = append(store, req)
|
||||
}
|
||||
} else {
|
||||
store = []entity.VersionConfig{req}
|
||||
}
|
||||
s.VersionByConfigId[req.ConfigId] = store
|
||||
return removedId
|
||||
}
|
||||
|
||||
func (s *VersionConfigStore) Delete(id string) {
|
||||
for cfgId, versionCfg := range s.VersionByConfigId {
|
||||
for i, versionConfig := range versionCfg {
|
||||
if versionConfig.Id == id {
|
||||
newVersionCfg := versionCfg[:i+copy(versionCfg[i:], versionCfg[i+1:])]
|
||||
if len(newVersionCfg) == 0 {
|
||||
delete(s.VersionByConfigId, cfgId)
|
||||
} else {
|
||||
s.VersionByConfigId[cfgId] = newVersionCfg
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s VersionConfigStore) GetByConfigId(id string) []entity.VersionConfig {
|
||||
response, found := s.VersionByConfigId[id]
|
||||
if found {
|
||||
return s.reverse(response)
|
||||
}
|
||||
return []entity.VersionConfig{}
|
||||
}
|
||||
|
||||
func (s VersionConfigStore) reverse(cfg []entity.VersionConfig) []entity.VersionConfig {
|
||||
for i, j := 0, len(cfg)-1; i < j; i, j = i+1, j-1 {
|
||||
cfg[i], cfg[j] = cfg[j], cfg[i]
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
func NewVersionConfigStore() *VersionConfigStore {
|
||||
return &VersionConfigStore{
|
||||
VersionByConfigId: make(map[string][]entity.VersionConfig),
|
||||
}
|
||||
}
|
||||
|
||||
func NewVersionConfigStoreFromSnapshot(req []entity.VersionConfig) *VersionConfigStore {
|
||||
store := NewVersionConfigStore()
|
||||
for i := 0; i < len(req); i++ {
|
||||
_ = store.Update(req[i])
|
||||
}
|
||||
return store
|
||||
}
|
||||
+6
-5
@@ -1,7 +1,6 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"sync"
|
||||
@@ -23,7 +22,7 @@ var (
|
||||
type Store struct {
|
||||
state *state.State
|
||||
lock sync.RWMutex
|
||||
handlers map[uint64]func([]byte) (interface{}, error)
|
||||
handlers map[cluster.Command]func([]byte) (interface{}, error)
|
||||
}
|
||||
|
||||
func (s *Store) Apply(l *raft.Log) interface{} {
|
||||
@@ -33,8 +32,8 @@ func (s *Store) Apply(l *raft.Log) interface{} {
|
||||
if len(l.Data) < cluster.CommandSizeBytes {
|
||||
log.Errorf(codes.ApplyLogCommandError, "invalid log data command: %s", l.Data)
|
||||
}
|
||||
command := binary.BigEndian.Uint64(l.Data[:8])
|
||||
log.Debugf(0, "Apply %d command. Data: %s", command, l.Data)
|
||||
command := cluster.ParseCommand(l.Data)
|
||||
log.Debugf(0, "Apply %s. Data: %s", command, l.Data)
|
||||
|
||||
var (
|
||||
result interface{}
|
||||
@@ -119,7 +118,7 @@ func NewStateStore(st *state.State) *Store {
|
||||
store := &Store{
|
||||
state: st,
|
||||
}
|
||||
store.handlers = map[uint64]func([]byte) (interface{}, error){
|
||||
store.handlers = map[cluster.Command]func([]byte) (interface{}, error){
|
||||
cluster.UpdateBackendDeclarationCommand: store.applyUpdateBackendDeclarationCommand,
|
||||
cluster.DeleteBackendDeclarationCommand: store.applyDeleteBackendDeclarationCommand,
|
||||
cluster.ModuleConnectedCommand: store.applyModuleConnectedCommand,
|
||||
@@ -131,6 +130,8 @@ func NewStateStore(st *state.State) *Store {
|
||||
cluster.UpsertConfigCommand: store.applyUpsertConfigCommand,
|
||||
cluster.DeleteCommonConfigsCommand: store.applyDeleteCommonConfigsCommand,
|
||||
cluster.UpsertCommonConfigCommand: store.applyUpsertCommonConfigCommand,
|
||||
cluster.BroadcastEventCommand: store.applyBroadcastEventCommand,
|
||||
cluster.DeleteVersionConfigCommand: store.applyDeleteVersionConfigCommand,
|
||||
}
|
||||
return store
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
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)
|
||||
}
|
||||
+12
-9
@@ -2,6 +2,7 @@ package subs
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/asaskevich/govalidator"
|
||||
etp "github.com/integration-system/isp-etp-go/v2"
|
||||
@@ -31,7 +32,7 @@ func (h *SocketEventHandler) handleModuleReady(conn etp.Conn, data []byte) []byt
|
||||
}
|
||||
SetBackendDeclaration(conn, declaration)
|
||||
command := cluster.PrepareUpdateBackendDeclarationCommand(declaration)
|
||||
_, err = SyncApplyCommand(command, "UpdateBackendDeclarationCommand")
|
||||
_, err = SyncApplyCommand(command)
|
||||
if err != nil {
|
||||
return []byte(err.Error())
|
||||
}
|
||||
@@ -52,9 +53,9 @@ func (h *SocketEventHandler) handleModuleRequirements(conn etp.Conn, data []byte
|
||||
}
|
||||
|
||||
h.store.VisitReadonlyState(func(state state.ReadonlyState) {
|
||||
service.DiscoveryService.Subscribe(conn, declaration.RequiredModules, state.Mesh())
|
||||
service.Discovery.Subscribe(conn, declaration.RequiredModules, state.Mesh())
|
||||
if declaration.RequireRoutes {
|
||||
service.RoutesService.SubscribeRoutes(conn, state.Mesh())
|
||||
service.Routes.SubscribeRoutes(conn, state.Mesh())
|
||||
}
|
||||
})
|
||||
return []byte(utils.WsOkResponse)
|
||||
@@ -90,13 +91,13 @@ func (h *SocketEventHandler) handleConfigSchema(conn etp.Conn, data []byte) []by
|
||||
UpdatedAt: now,
|
||||
}
|
||||
command := cluster.PrepareUpdateConfigSchemaCommand(schema)
|
||||
_, _ = SyncApplyCommand(command, "UpdateConfigSchemaCommand")
|
||||
_, _ = SyncApplyCommand(command)
|
||||
|
||||
var configs []entity.Config
|
||||
h.store.VisitReadonlyState(func(readState state.ReadonlyState) {
|
||||
configs = readState.Configs().GetByModuleIds([]string{module.Id})
|
||||
})
|
||||
if len(configs) == 0 { //create empty default config
|
||||
if len(configs) == 0 { // create empty default config
|
||||
if configSchema.DefaultConfig == nil {
|
||||
configSchema.DefaultConfig = make(map[string]interface{})
|
||||
}
|
||||
@@ -109,13 +110,15 @@ func (h *SocketEventHandler) handleConfigSchema(conn etp.Conn, data []byte) []by
|
||||
UpdatedAt: now,
|
||||
}
|
||||
upsertConfig := cluster.UpsertConfig{
|
||||
Config: config,
|
||||
Create: true,
|
||||
Unsafe: true,
|
||||
Config: config,
|
||||
Create: true,
|
||||
Unsafe: true,
|
||||
VersionId: state.GenerateId(),
|
||||
VersionCreateAt: time.Now(),
|
||||
}
|
||||
|
||||
command := cluster.PrepareUpsertConfigCommand(upsertConfig)
|
||||
_, _ = SyncApplyCommand(command, "UpsertConfigCommand")
|
||||
_, _ = SyncApplyCommand(command)
|
||||
}
|
||||
return []byte(utils.WsOkResponse)
|
||||
}
|
||||
+4
-2
@@ -1,6 +1,8 @@
|
||||
package subs
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
etp "github.com/integration-system/isp-etp-go/v2"
|
||||
log "github.com/integration-system/isp-log"
|
||||
"isp-config-service/cluster"
|
||||
@@ -14,8 +16,8 @@ func (h *SocketEventHandler) applyCommandOnLeader(_ etp.Conn, cmd []byte) (data
|
||||
obj, err := holder.ClusterClient.SyncApplyOnLeader(cmdCopy)
|
||||
if err != nil {
|
||||
var logResponse cluster.ApplyLogResponse
|
||||
logResponse.ApplyError = err.Error()
|
||||
data, err = json.Marshal(obj)
|
||||
logResponse.ApplyError = fmt.Sprintf("SyncApplyOnLeader: %v", err)
|
||||
data, err = json.Marshal(logResponse)
|
||||
if err != nil {
|
||||
log.Fatalf(codes.SyncApplyError, "marshaling ApplyLogResponse: %v", err)
|
||||
}
|
||||
|
||||
+1
-2
@@ -12,12 +12,11 @@ type connectionState struct {
|
||||
}
|
||||
|
||||
func IsConfigClusterNode(conn etp.Conn) bool {
|
||||
isCluster := conn.URL().Query().Get(cluster.ClusterParam)
|
||||
isCluster := conn.URL().Query().Get(cluster.GETParam)
|
||||
return isCluster == "true"
|
||||
}
|
||||
|
||||
func Parameters(conn etp.Conn) (moduleName string, err error) {
|
||||
// TODO remove instanceUUID from isp-lib
|
||||
_, moduleName, err = utils.ParseParameters(conn.URL().RawQuery)
|
||||
return moduleName, err
|
||||
}
|
||||
|
||||
+7
-4
@@ -1,17 +1,18 @@
|
||||
package subs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
etp "github.com/integration-system/isp-etp-go/v2"
|
||||
log "github.com/integration-system/isp-log"
|
||||
"isp-config-service/cluster"
|
||||
"isp-config-service/codes"
|
||||
"isp-config-service/holder"
|
||||
"isp-config-service/service"
|
||||
)
|
||||
|
||||
func EmitConn(conn etp.Conn, event string, body []byte) {
|
||||
err := conn.Emit(context.Background(), event, body)
|
||||
err := service.EmitConnWithTimeout(conn, event, body)
|
||||
if err != nil {
|
||||
log.WithMetadata(map[string]interface{}{
|
||||
"event": event,
|
||||
@@ -19,9 +20,10 @@ func EmitConn(conn etp.Conn, event string, body []byte) {
|
||||
}
|
||||
}
|
||||
|
||||
func SyncApplyCommand(command []byte, commandName string) (interface{}, error) {
|
||||
func SyncApplyCommand(command []byte) (interface{}, error) {
|
||||
applyLogResponse, err := holder.ClusterClient.SyncApply(command)
|
||||
if err != nil {
|
||||
commandName := cluster.ParseCommand(command).String()
|
||||
log.WithMetadata(map[string]interface{}{
|
||||
"command": string(command),
|
||||
"commandName": commandName,
|
||||
@@ -29,6 +31,7 @@ func SyncApplyCommand(command []byte, commandName string) (interface{}, error) {
|
||||
return nil, err
|
||||
}
|
||||
if applyLogResponse != nil && applyLogResponse.ApplyError != "" {
|
||||
commandName := cluster.ParseCommand(command).String()
|
||||
log.WithMetadata(map[string]interface{}{
|
||||
"result": string(applyLogResponse.Result),
|
||||
"applyError": applyLogResponse.ApplyError,
|
||||
@@ -41,7 +44,7 @@ func SyncApplyCommand(command []byte, commandName string) (interface{}, error) {
|
||||
|
||||
func FormatErrorConnection(err error) []byte {
|
||||
errMap := map[string]interface{}{
|
||||
"error": err,
|
||||
"error": err.Error(),
|
||||
}
|
||||
data, _ := json.Marshal(errMap)
|
||||
return data
|
||||
|
||||
+12
-11
@@ -43,7 +43,7 @@ func (h *SocketEventHandler) handleConnect(conn etp.Conn) {
|
||||
_ = conn.Close()
|
||||
return
|
||||
}
|
||||
holder.EtpServer.Rooms().Join(conn, moduleName+service.ConfigWatchersRoomSuffix)
|
||||
holder.EtpServer.Rooms().Join(conn, service.Room.Module(moduleName))
|
||||
now := state.GenerateDate()
|
||||
module := entity.Module{
|
||||
Id: state.GenerateId(),
|
||||
@@ -52,7 +52,7 @@ func (h *SocketEventHandler) handleConnect(conn etp.Conn) {
|
||||
LastConnectedAt: now,
|
||||
}
|
||||
command := cluster.PrepareModuleConnectedCommand(module)
|
||||
_, err = SyncApplyCommand(command, "ModuleConnectedCommand")
|
||||
_, err = SyncApplyCommand(command)
|
||||
if err != nil && !isClusterNode {
|
||||
EmitConn(conn, utils.ErrorConnection, FormatErrorConnection(err))
|
||||
_ = conn.Close()
|
||||
@@ -79,11 +79,11 @@ 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, _ error) {
|
||||
moduleName, _ := Parameters(conn)
|
||||
log.Debugf(0, "handleDisconnect from %s", moduleName) // REMOVE
|
||||
log.Debugf(0, "websocket handleDisconnect from module '%s' addr '%s'", moduleName, conn.RemoteAddr())
|
||||
if moduleName != "" {
|
||||
holder.EtpServer.Rooms().Leave(conn, moduleName+service.ConfigWatchersRoomSuffix)
|
||||
holder.EtpServer.Rooms().Leave(conn, service.Room.Module(moduleName))
|
||||
now := state.GenerateDate()
|
||||
module := entity.Module{
|
||||
Id: state.GenerateId(),
|
||||
@@ -93,20 +93,21 @@ func (h *SocketEventHandler) handleDisconnect(conn etp.Conn, disconnectErr error
|
||||
LastDisconnectedAt: now,
|
||||
}
|
||||
command := cluster.PrepareModuleDisconnectedCommand(module)
|
||||
_, _ = SyncApplyCommand(command, "ModuleDisconnectedCommand")
|
||||
_, _ = SyncApplyCommand(command)
|
||||
}
|
||||
|
||||
service.DiscoveryService.HandleDisconnect(conn.ID())
|
||||
service.RoutesService.HandleDisconnect(conn.ID())
|
||||
service.Discovery.HandleDisconnect(conn.ID())
|
||||
service.Routes.HandleDisconnect(conn.ID())
|
||||
backend, ok := ExtractBackendDeclaration(conn)
|
||||
if ok {
|
||||
command := cluster.PrepareDeleteBackendDeclarationCommand(backend)
|
||||
_, _ = SyncApplyCommand(command, "DeleteBackendDeclarationCommand")
|
||||
_, _ = SyncApplyCommand(command)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *SocketEventHandler) handleError(_ etp.Conn, err error) {
|
||||
log.Warnf(codes.WebsocketError, "isp-etp: %v", err)
|
||||
func (h *SocketEventHandler) handleError(conn etp.Conn, err error) {
|
||||
moduleName, _ := Parameters(conn)
|
||||
log.Warnf(codes.WebsocketError, "websocket handleError module '%s' from %s: %v", moduleName, conn.RemoteAddr(), err)
|
||||
}
|
||||
|
||||
func NewSocketEventHandler(server etp.Server, store *store.Store) *SocketEventHandler {
|
||||
|
||||
Reference in new issue
Block a user