Compare commits

...
Author SHA1 Message Date
komissarovyv 818ee18544 Fix build 2025-01-28 17:42:04 +03:00
Кузьмин Игорь Александрович abf6a37c7a Upload New File 2025-01-28 14:12:31 +00:00
Кузьмин Игорь Александрович c2af71449a Upload New File 2025-01-28 14:05:56 +00:00
d1slike 05eb762273 Fix data 2024-04-24 17:34:03 +03:00
Кузьмин Игорь Александрович e2419e2c4b Update file README.md 2024-03-25 14:40:05 +00:00
Кузьмин Игорь Александрович 72afc94782 Update README.md 2024-03-25 14:04:00 +00:00
Кузьмин Игорь Александрович 02070b1db1 Update file README.md 2024-03-25 13:50:01 +00:00
Кузьмин Игорь Александрович 2fc6c7ba91 Delete Dockerfile.dit 2024-03-25 13:16:38 +00:00
Кузьмин Игорь Александрович c706d7932d Delete .gitlab-ci.yml 2024-03-25 13:16:28 +00:00
Кузьмин Игорь 62714cdfe1 Upload New File 2023-05-10 08:44:16 +00:00
Кузьмин Игорь a2c49ac39f Add new file 2023-05-03 10:11:43 +00:00
komissarovyv de55ea643c Merge branch 'deps' into 'master'
Deps

See merge request integration-system/isp-config-service!6
2022-12-09 09:09:04 +00:00
d1slike 5fb60e14b8 Ignore test 2022-12-08 16:35:34 +03:00
d1slike 02603cb018 Bump version 2022-12-08 16:22:25 +03:00
d1slike ffbff595d1 Remove ci 2022-12-08 16:18:01 +03:00
d1slike 989429824e Upgrade dependencies 2022-12-08 16:18:01 +03:00
Кузьмин Игорь a31e6080e2 Update default_remote_config.json 2022-11-29 11:56:09 +00:00
Кузьмин Игорь 90e05dfb4b Add new file 2022-11-29 11:51:08 +00:00
Мержанов Максим Владимирович 2af27ddb68 Merge branch 'remove_instance_uuid' into 'master'
remove instanceUuid

See merge request integration-system/isp-config-service!5
2021-05-26 14:08:58 +00:00
Maxim Merzhanov d004faa9e0 remove instanceUuid 2021-05-25 18:39:58 +03:00
Мержанов Максим Владимирович 45a4a23112 Merge branch '__deps' into 'master'
Update dependencies

See merge request integration-system/isp-config-service!4
2021-05-18 12:09:02 +00:00
Egor Kiryushchenko 1bb50f8175 Update dependencies 2021-05-17 16:22:07 +03:00
Мержанов Максим Владимирович 0cbfcab3f9 Merge branch 'bugfixes' into 'master'
Bugfixes

See merge request integration-system/isp-config-service!3
2021-05-14 09:36:25 +00:00
Maxim Merzhanov d4125963b2 update CHANGELOG.md 2021-05-13 17:35:22 +03:00
Maxim Merzhanov 2e33c2275c address review comments
- increase shutdown limit to 10/11 sec as it was set in isp-lib/bootstrap
- refactor
- update libs versions to released
2021-05-13 17:04:15 +03:00
Maxim Merzhanov a5b21198e0 cluster: reduce websocket read buffer from 10 to 1 2021-04-30 18:05:06 +03:00
Maxim Merzhanov e765cda3f9 add timeouts to all websocket emits 2021-04-30 13:09:52 +03:00
Maxim Merzhanov 5a91184d6c fix deadlock in cluster client 2021-04-22 19:25:35 +03:00
Maxim Merzhanov e2094296f4 fix race in test (TimeoutRetryer.Do needs to be fixed in isp-lib-test) 2021-04-22 19:16:26 +03:00
Maxim Merzhanov 777e856d00 fix potential error shadowing when leader apply log, but return nil instead of ApplyLogResponse 2021-04-21 17:04:48 +03:00
Maxim Merzhanov c3f419bbc5 update raft lib, improve raft logging 2021-04-21 16:47:59 +03:00
Maxim Merzhanov 52705f6982 fix hanging on graceful shutdown 2021-04-21 16:47:59 +03:00
Maxim Merzhanov a5134181be add integration test for multiple config updates 2021-04-19 10:25:43 +03:00
Maxim Merzhanov 79c801d493 add metric server 2021-04-05 18:42:54 +03:00
Maxim Merzhanov f9823d5303 fix version config store test 2021-04-01 18:55:08 +03:00
Maxim Merzhanov 8339591b27 fix leader address race on leader disconnect 2021-04-01 18:36:12 +03:00
Maxim Merzhanov 17a6e3186d fix a couple of data races 2021-04-01 16:54:42 +03:00
Maxim Merzhanov 213bad9722 increase default version config count to 15 2021-04-01 16:47:44 +03:00
Maxim Merzhanov ef33bd9fd2 up test lib, fix grpc awaiting 2021-03-10 11:41:36 +03:00
Мержанов Максим Владимирович 123de3d452 Merge branch '__deps' into 'master'
Update dependencies

See merge request integration-system/isp-config-service!2
2021-01-26 19:21:26 +03:00
Egor Kiryushchenko 6591bff728 Update dependencies 2021-01-26 13:52:14 +03:00
Maxim Merzhanov 88c0779aa2 fix marshaling body of ERROR_CONNECTION event 2021-01-15 16:05:47 +03:00
Максим Мержанов 95adcb117c Merge branch '__deps' into 'master'
Update dependencies

See merge request integration-system/isp-config-service!14
2020-11-24 16:56:15 +03:00
Egor Kiryushchenko 372636f43b Update dependencies 2020-11-24 09:42:16 +03:00
Maxim Merzhanov 54dae1ab2b fix test 2020-11-23 10:47:08 +03:00
Egor Kiryushchenko f0f50a8507 fix lint 2020-11-20 16:46:46 +03:00
Egor Kiryushchenko c3d0d5be4c Update dependencies 2020-11-19 10:29:59 +03:00
DeniskaRediska 929132743c up version 2020-10-22 15:51:52 +03:00
DeniskaRediska 6643e8937c add db pass part 2020-10-22 15:49:25 +03:00
Максим Мержанов 08b4ee461e Merge branch 'api_ext_branch' into 'master'
add valid property to method `/config/get_configs_by_module_id`

See merge request integration-system/isp-config-service!6
2020-09-28 16:08:21 +03:00
Рябов Владислав Олегович ae501969bf add valid property to method /config/get_configs_by_module_id 2020-09-28 16:08:21 +03:00
Максим Мержанов c29ed6d41e Merge branch 'api_ext_branch' into 'master'
add new config methods

See merge request integration-system/isp-config-service!5
2020-09-24 22:08:50 +03:00
Рябов Владислав Олегович 1c28c895b5 add new config methods 2020-09-24 22:08:50 +03:00
d1slike d9c32437c9 remove utc 2020-07-15 17:37:22 +03:00
d1slike 0429bed9e3 up version 2020-07-15 17:33:06 +03:00
DeniskaRediska 8bdc36a302 up created_at for version_config 2020-07-10 19:48:09 +03:00
DeniskaRediska a3576cc3f4 add created_at for version_config 2020-07-10 19:38:35 +03:00
DeniskaRediska 713db0aa4c reverse version config 2020-07-10 19:26:35 +03:00
d1slike 95aae06a41 downgrade version 2020-06-09 14:42:36 +03:00
DeniskaRediska 31a4a6f5b8 ref 2020-06-09 13:55:39 +03:00
DeniskaRediska 1c66729974 fix generate version id 2020-06-09 13:41:56 +03:00
d1slike 6387947b22 small ref 2020-06-09 12:57:07 +03:00
DeniskaRediska 3a8469c5a9 fix test 2020-06-08 20:44:54 +03:00
DeniskaRediska 44715591ef fix lint 2020-06-08 20:14:50 +03:00
DeniskaRediska ceb9d71a1a fix lint 2020-06-08 20:11:53 +03:00
DeniskaRediska 15ad05277b add config version 2020-06-08 18:39:25 +03:00
d1slike 14c5b0a678 fix broadcasting config on activating and upserting configs 2020-06-03 15:43:05 +03:00
d1slike c95964fa3c get module dependencies from first connected backend 2020-06-03 14:35:11 +03:00
d1slike a46f2cee34 Merge remote-tracking branch 'origin/required_modules' into feat_broadcasting
# Conflicts:
#	go.mod
#	go.sum
2020-06-03 14:10:14 +03:00
d1slike 1764ce9a30 Merge remote-tracking branch 'origin/add_conf_version' into feat_broadcasting
# Conflicts:
#	go.mod
#	go.sum
2020-06-03 14:09:57 +03:00
DeniskaRediska 384fa0417a add config version 2020-06-03 11:33:52 +03:00
Maxim Merzhanov 97ba1050a7 appease linter 2020-06-02 18:19:33 +03:00
Maxim Merzhanov 628c506e85 list required modules in get_modules_info method 2020-06-02 17:06:02 +03:00
d1slike 9226796463 broadcasting to modules 2020-06-01 19:35:22 +03:00
Maxim Merzhanov 83176ba878 update doc 2020-03-24 13:24:16 +03:00
Maxim Merzhanov 94cb067214 refactor sync apply helpers 2020-03-23 18:31:47 +03:00
Maxim Merzhanov b56b6e0e42 update isp-etp lib 2020-03-23 17:51:30 +03:00
Maxim Merzhanov 28aa3eae33 add module/broadcast_event method 2020-03-23 16:49:21 +03:00
Maxim Merzhanov 96dee8dee3 stringify cluster commands in log 2020-03-23 12:49:34 +03:00
Maxim Merzhanov 400410c449 up version 2020-03-23 12:17:37 +03:00
Maxim Merzhanov ab08abb3f6 fix integration test 2020-03-23 11:50:04 +03:00
Maxim Merzhanov 01e32537a8 update docs 2020-03-23 11:21:23 +03:00
Maxim Merzhanov 652d1c8c4f update isp-lib and go-pg 2020-03-23 11:16:30 +03:00
63 changed files with 2239 additions and 1255 deletions

No files matched your search

+23
View File
@@ -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
-39
View File
@@ -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 # в данном проекте не нужен
+1 -1
View File
@@ -1 +1 @@
2.2.0 2.4.9
+49 -1
View File
@@ -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 ### v2.2.0
* migrate to go modules * migrate to go modules
* add linter, refactor * add linter, refactor
@@ -12,7 +60,7 @@
* update to new endpoint descriptor struct with extra fields introduced in isp-lib v2.1.0 * update to new endpoint descriptor struct with extra fields introduced in isp-lib v2.1.0
### v2.1.0 ### v2.1.0
* fix panic type casting in shapshot * fix panic type casting in snapshot
* create empty default config now * create empty default config now
* add method `/module/get_by_name` to fetch module object by name * add method `/module/get_by_name` to fetch module object by name
+41
View File
@@ -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
+1
View File
@@ -0,0 +1 @@
test
+36 -29
View File
@@ -2,9 +2,11 @@ package cluster
import ( import (
"errors" "errors"
"fmt"
"sync" "sync"
"time" "time"
"github.com/integration-system/isp-lib/v2/atomic"
"github.com/integration-system/isp-lib/v2/structure" "github.com/integration-system/isp-lib/v2/structure"
"github.com/integration-system/isp-lib/v2/utils" "github.com/integration-system/isp-lib/v2/utils"
log "github.com/integration-system/isp-log" log "github.com/integration-system/isp-log"
@@ -31,6 +33,7 @@ type Client struct {
r *raft.Raft r *raft.Raft
leaderMu sync.RWMutex leaderMu sync.RWMutex
isLeader *atomic.AtomicBool
leaderState leaderState leaderState leaderState
leaderClient *SocketLeaderClient leaderClient *SocketLeaderClient
declaration structure.BackendDeclaration declaration structure.BackendDeclaration
@@ -50,10 +53,7 @@ func (client *Client) Shutdown() error {
} }
func (client *Client) IsLeader() bool { func (client *Client) IsLeader() bool {
client.leaderMu.RLock() return client.isLeader.Get()
defer client.leaderMu.RUnlock()
return client.leaderState.isLeader
} }
func (client *Client) SyncApply(command []byte) (*ApplyLogResponse, error) { func (client *Client) SyncApply(command []byte) (*ApplyLogResponse, error) {
@@ -67,25 +67,27 @@ func (client *Client) SyncApply(command []byte) (*ApplyLogResponse, error) {
if client.leaderState.isLeader { if client.leaderState.isLeader {
apply, err := client.r.SyncApply(command) apply, err := client.r.SyncApply(command)
if err != nil { if err != nil {
return nil, err return nil, fmt.Errorf("apply to raft as a leader: %v", err)
} }
logResponse := apply.(ApplyLogResponse) 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 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) { 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) apply, err := client.r.SyncApply(command)
if err != nil { if err != nil {
return nil, err return nil, fmt.Errorf("apply to raft as a leader: %v", err)
} }
logResponse := apply.(ApplyLogResponse) logResponse := apply.(ApplyLogResponse)
return &logResponse, err return &logResponse, nil
} }
func (client *Client) listenLeader() { func (client *Client) listenLeader() {
@@ -113,17 +115,16 @@ func (client *Client) listenLeader() {
}).Info(codes.LeaderStateChanged, "leader state changed") }).Info(codes.LeaderStateChanged, "leader state changed")
if client.leaderClient != nil { if client.leaderClient != nil {
log.Debugf(0, "close previous leader ws connection %s", client.leaderState.leaderAddr)
client.leaderClient.Close() client.leaderClient.Close()
client.leaderClient = nil client.leaderClient = nil
} }
if n.LeaderElected && !n.IsLeader { if n.LeaderElected && !n.IsLeader {
leaderClient := NewSocketLeaderClient(n.CurrentLeaderAddress, func() { leaderAddr := n.CurrentLeaderAddress
client.onClientDisconnect(client.leaderState.leaderAddr) leaderClient := NewSocketLeaderClient(leaderAddr, func() {
client.onClientDisconnect(leaderAddr)
}) })
if err := leaderClient.Dial(leaderConnectionTimeout); err != nil { if err := leaderClient.Dial(leaderConnectionTimeout); err != nil {
log.Fatalf(codes.LeaderClientConnectionError, "could not connect to leader: %v", err) log.Fatalf(codes.LeaderClientConnectionError, "could not connect to leader: %v", err)
continue
} }
client.leaderClient = leaderClient client.leaderClient = leaderClient
@@ -137,6 +138,7 @@ func (client *Client) listenLeader() {
isLeader: n.IsLeader, isLeader: n.IsLeader,
leaderAddr: n.CurrentLeaderAddress, leaderAddr: n.CurrentLeaderAddress,
} }
client.isLeader.Set(n.IsLeader)
client.leaderMu.Unlock() client.leaderMu.Unlock()
} }
@@ -146,7 +148,9 @@ func (client *Client) declareMyselfToLeader(leaderClient *SocketLeaderClient) {
if err != nil { if err != nil {
log.Warnf(codes.SendDeclarationToLeader, "send declaration to leader. err: %v", err) log.Warnf(codes.SendDeclarationToLeader, "send declaration to leader. err: %v", err)
} else if response != utils.WsOkResponse { } 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, LastConnectedAt: now,
} }
command := PrepareModuleConnectedCommand(module) command := PrepareModuleConnectedCommand(module)
syncApplyCommand(client, command, "ModuleConnectedCommand") syncApplyCommand(client, command)
declarationCommand := PrepareUpdateBackendDeclarationCommand(client.declaration) declarationCommand := PrepareUpdateBackendDeclarationCommand(client.declaration)
syncApplyCommand(client, declarationCommand, "UpdateBackendDeclarationCommand") syncApplyCommand(client, declarationCommand)
} }
type leaderState struct { type leaderState struct {
@@ -178,21 +182,24 @@ func NewRaftClusterClient(r *raft.Raft, declaration structure.BackendDeclaration
declaration: declaration, declaration: declaration,
leaderState: leaderState{}, leaderState: leaderState{},
onClientDisconnect: onLeaderDisconnect, onClientDisconnect: onLeaderDisconnect,
isLeader: atomic.NewAtomicBool(false),
} }
go client.listenLeader() go client.listenLeader()
return client return client
} }
func syncApplyCommand(clusterClient *Client, command []byte, commandName string) { func syncApplyCommand(clusterClient *Client, command []byte) {
applyLogResponse, err := clusterClient.SyncApply(command) applyLogResponse, err := clusterClient.SyncApply(command)
if err != nil { if err != nil {
commandName := ParseCommand(command).String()
log.WithMetadata(map[string]interface{}{ log.WithMetadata(map[string]interface{}{
"command": string(command), "command": string(command),
"commandName": commandName, "commandName": commandName,
}).Warnf(codes.SyncApplyError, "announce myself. apply command: %v", err) }).Warnf(codes.SyncApplyError, "announce myself. apply command: %v", err)
} }
if applyLogResponse != nil && applyLogResponse.ApplyError != "" { if applyLogResponse != nil && applyLogResponse.ApplyError != "" {
commandName := ParseCommand(command).String()
log.WithMetadata(map[string]interface{}{ log.WithMetadata(map[string]interface{}{
"result": string(applyLogResponse.Result), "result": string(applyLogResponse.Result),
"applyError": applyLogResponse.ApplyError, "applyError": applyLogResponse.ApplyError,
+25 -4
View File
@@ -15,10 +15,16 @@ const (
ApplyCommandEvent = "CONFIG_CLUSTER:APPLY_COMMAND" ApplyCommandEvent = "CONFIG_CLUSTER:APPLY_COMMAND"
CommandSizeBytes = 8 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 ( const (
_ = iota _ Command = iota
UpdateBackendDeclarationCommand UpdateBackendDeclarationCommand
DeleteBackendDeclarationCommand DeleteBackendDeclarationCommand
@@ -27,6 +33,7 @@ const (
ModuleConnectedCommand ModuleConnectedCommand
ModuleDisconnectedCommand ModuleDisconnectedCommand
DeleteModulesCommand DeleteModulesCommand
DeleteVersionConfigCommand
ActivateConfigCommand ActivateConfigCommand
DeleteConfigsCommand DeleteConfigsCommand
@@ -34,8 +41,14 @@ const (
DeleteCommonConfigsCommand DeleteCommonConfigsCommand
UpsertCommonConfigCommand UpsertCommonConfigCommand
BroadcastEventCommand
) )
func ParseCommand(data []byte) Command {
return Command(binary.BigEndian.Uint64(data[:CommandSizeBytes]))
}
func PrepareUpdateBackendDeclarationCommand(backend structure.BackendDeclaration) []byte { func PrepareUpdateBackendDeclarationCommand(backend structure.BackendDeclaration) []byte {
return prepareCommand(UpdateBackendDeclarationCommand, backend) return prepareCommand(UpdateBackendDeclarationCommand, backend)
} }
@@ -80,9 +93,17 @@ func PrepareUpsertCommonConfigCommand(config UpsertCommonConfig) []byte {
return prepareCommand(UpsertCommonConfigCommand, config) 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) cmd := make([]byte, 8)
binary.BigEndian.PutUint64(cmd, command) binary.BigEndian.PutUint64(cmd, uint64(command))
buf := bytes.NewBuffer(cmd) buf := bytes.NewBuffer(cmd)
err := json.NewEncoder(buf).Encode(payload) err := json.NewEncoder(buf).Encode(payload)
if err != nil { if err != nil {
+36
View File
@@ -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
View File
@@ -3,9 +3,10 @@ package cluster
import ( import (
json2 "encoding/json" json2 "encoding/json"
"fmt" "fmt"
"time"
"google.golang.org/grpc/codes" "google.golang.org/grpc/codes"
"isp-config-service/entity" "isp-config-service/entity"
"time"
) )
type ApplyLogResponse struct { type ApplyLogResponse struct {
@@ -27,9 +28,11 @@ type ActivateConfig struct {
} }
type UpsertConfig struct { type UpsertConfig struct {
Config entity.Config Config entity.Config
Create bool VersionId string
Unsafe bool VersionCreateAt time.Time
Create bool
Unsafe bool
} }
type DeleteConfigs struct { type DeleteConfigs struct {
@@ -40,11 +43,22 @@ type DeleteCommonConfig struct {
Id string Id string
} }
type Identity struct {
Id string
}
type UpsertCommonConfig struct { type UpsertCommonConfig struct {
Config entity.CommonConfig Config entity.CommonConfig
Create bool 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 { type ResponseWithError struct {
Response interface{} Response interface{}
Error string Error string
+12 -8
View File
@@ -62,15 +62,17 @@ func (c *SocketLeaderClient) Close() {
c.cancel() c.cancel()
err := c.client.Close() err := c.client.Close()
if err != nil { 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 { func NewSocketLeaderClient(address string, leaderDisconnectionCallback func()) *SocketLeaderClient {
etpConfig := etp.Config{ etpConfig := etp.Config{
HttpClient: http.DefaultClient, HttpClient: &http.Client{},
ConnectionReadLimit: WsConnectionReadLimit, ConnectionReadLimit: WsConnectionReadLimit,
WorkersNum: 1,
WorkersBufferMultiplier: 1,
} }
client := etp.NewClient(etpConfig) client := etp.NewClient(etpConfig)
leaderClient := &SocketLeaderClient{ leaderClient := &SocketLeaderClient{
@@ -84,12 +86,16 @@ func NewSocketLeaderClient(address string, leaderDisconnectionCallback func()) *
leaderClient.client.OnDisconnect(func(err error) { leaderClient.client.OnDisconnect(func(err error) {
log.WithMetadata(map[string]interface{}{ log.WithMetadata(map[string]interface{}{
"leaderAddr": address, "leaderAddr": address,
"error": err,
}).Warn(codes.LeaderClientDisconnected, "disconnected ws from leader") }).Warn(codes.LeaderClientDisconnected, "disconnected ws from leader")
leaderDisconnectionCallback() leaderDisconnectionCallback()
}) })
leaderClient.client.OnError(func(err error) { 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() { leaderClient.client.OnConnect(func() {
log.WithMetadata(map[string]interface{}{ log.WithMetadata(map[string]interface{}{
@@ -107,9 +113,7 @@ func getURL(address string) string {
cfg := config.Get().(*conf.Configuration) cfg := config.Get().(*conf.Configuration)
params := url.Values{} params := url.Values{}
params.Add(ClusterParam, "true") params.Add(GETParam, "true")
// TODO выпилить instance_uuid ?
params.Add(utils.ModuleNameGetParamKey, cfg.ModuleName) 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()) return fmt.Sprintf("ws://%s:%d/isp-etp/?%s", addr.IP.String(), addr.Port, params.Encode())
} }
+2
View File
@@ -37,3 +37,5 @@ cluster:
bootstrapCluster: true bootstrapCluster: true
peers: peers:
- 127.0.0.1:9001 - 127.0.0.1:9001
versionConfigCount: 15
-3
View File
@@ -1,10 +1,7 @@
moduleName: config moduleName: config
instanceUuid: bf482806-0c3d-4e0d-b9d4-12c037b12d70
registry: registry:
host: nexus.msp.mobi host: nexus.msp.mobi
username: mp3deployer
password: ScjKLQuvqfAXu2bs8ysLAvRt
images: images:
module: nexus.msp.mobi/msp2/dev/isp-config-service:latest module: nexus.msp.mobi/msp2/dev/isp-config-service:latest
+8 -7
View File
@@ -1,4 +1,4 @@
//nolint lll //nolint:lll
package conf package conf
import ( import (
@@ -6,12 +6,13 @@ import (
) )
type Configuration struct { type Configuration struct {
Database structure.DBConfiguration `valid:"required~Required" schema:"База данных,настройка параметров подключения к базе данных"` Database structure.DBConfiguration `valid:"required~Required" schema:"База данных,настройка параметров подключения к базе данных"`
GrpcOuterAddress structure.AddressConfiguration `valid:"required~Required" json:"grpcOuterAddress"` GrpcOuterAddress structure.AddressConfiguration `valid:"required~Required" json:"grpcOuterAddress"`
ModuleName string `valid:"required~Required"` ModuleName string `valid:"required~Required"`
WS WebService `valid:"required~Required" schema:"Конфигурация веб сервиса"` WS WebService `valid:"required~Required" schema:"Конфигурация веб сервиса"`
Metrics structure.MetricConfiguration Metrics structure.MetricConfiguration
Cluster ClusterConfiguration `valid:"required~Required"` Cluster ClusterConfiguration `valid:"required~Required"`
VersionConfigCount int `schema:"Количество сохраняемых старых версий конфигурации"`
} }
type ClusterConfiguration struct { type ClusterConfiguration struct {
+1
View File
@@ -0,0 +1 @@
{}
-336
View File
@@ -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
View File
@@ -15,12 +15,11 @@ type commonConfig struct {
rstore *store.Store rstore *store.Store
} }
// GetConfigs godoc
// @Summary Метод получения объектов конфигурации по идентификаторам // @Summary Метод получения объектов конфигурации по идентификаторам
// @Description Возвращает массив конфигураций по запрошенным идентификаторам (все, если массив пустой) // @Description Возвращает массив конфигураций по запрошенным идентификаторам (все, если массив пустой)
// @Tags Общие конфигурации // @Tags Общие конфигурации
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Success 200 {array} entity.CommonConfig // @Success 200 {array} entity.CommonConfig
// @Router /common_config/get_configs [POST] // @Router /common_config/get_configs [POST]
func (c *commonConfig) GetConfigs(identities []string) []entity.CommonConfig { func (c *commonConfig) GetConfigs(identities []string) []entity.CommonConfig {
@@ -35,13 +34,12 @@ func (c *commonConfig) GetConfigs(identities []string) []entity.CommonConfig {
return response return response
} }
// CreateUpdateConfig godoc
// @Summary Метод обновления общей конфигурации // @Summary Метод обновления общей конфигурации
// @Description Если конфиг с таким id существует, то обновляет данные, если нет, то добавляет данные в базу // @Description Если конфиг с таким id существует, то обновляет данные, если нет, то добавляет данные в базу
// В случае обновления рассылает все подключенным модулям актуальную конфигурацию // @Description В случае обновления рассылает всем подключенным модулям актуальную конфигурацию
// @Tags Общие конфигурации // @Tags Общие конфигурации
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param body body entity.CommonConfig true "объект для сохранения" // @Param body body entity.CommonConfig true "объект для сохранения"
// @Success 200 {object} entity.CommonConfig // @Success 200 {object} entity.CommonConfig
// @Failure 404 {object} structure.GrpcError "если конфигурация не найдена" // @Failure 404 {object} structure.GrpcError "если конфигурация не найдена"
@@ -60,19 +58,18 @@ func (c *commonConfig) CreateUpdateConfig(config entity.CommonConfig) (*entity.C
upsertConfig.Create = true upsertConfig.Create = true
} }
command := cluster.PrepareUpsertCommonConfigCommand(upsertConfig) command := cluster.PrepareUpsertCommonConfigCommand(upsertConfig)
err := PerformSyncApplyWithError(command, "UpsertCommonConfigCommand", &response) err := PerformSyncApplyWithError(command, &response)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &response, nil return &response, nil
} }
// DeleteConfigs godoc
// @Summary Метод удаления объектов общей конфигурации по идентификаторам // @Summary Метод удаления объектов общей конфигурации по идентификаторам
// @Description Возвращает флаг удаления и набор связей с модулями и конфигурациями, в случае наличия связей deleted всегда false // @Description Возвращает флаг удаления и набор связей с модулями и конфигурациями, в случае наличия связей deleted всегда false
// @Tags Общие конфигурации // @Tags Общие конфигурации
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param body body domain.ConfigIdRequest true "id общей конфигурации" // @Param body body domain.ConfigIdRequest true "id общей конфигурации"
// @Success 200 {object} domain.DeleteCommonConfigResponse // @Success 200 {object} domain.DeleteCommonConfigResponse
// @Failure 500 {object} structure.GrpcError // @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) { func (c *commonConfig) DeleteConfigs(req domain.ConfigIdRequest) (*domain.DeleteCommonConfigResponse, error) {
var response domain.DeleteCommonConfigResponse var response domain.DeleteCommonConfigResponse
command := cluster.PrepareDeleteCommonConfigsCommand(req.Id) command := cluster.PrepareDeleteCommonConfigsCommand(req.Id)
err := PerformSyncApplyWithError(command, "DeleteCommonConfigsCommand", &response) err := PerformSyncApplyWithError(command, &response)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &response, nil return &response, nil
} }
// CompileConfigs godoc
// @Summary Метод компиляции итоговой конфигурации для модулей // @Summary Метод компиляции итоговой конфигурации для модулей
// @Description Возвращает скомпилированный объект конфигурации // @Description Возвращает скомпилированный объект конфигурации
// @Tags Общие конфигурации // @Tags Общие конфигурации
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param body body domain.CompileConfigsRequest true "перечисление идентификаторов общей конфигурации и исхдных конфиг" // @Param body body domain.CompileConfigsRequest true "перечисление идентификаторов общей конфигурации и исхдных конфиг"
// @Success 200 {object} domain.CompiledConfigResponse // @Success 200 {object} domain.CompiledConfigResponse
// @Router /common_config/compile [POST] // @Router /common_config/compile [POST]
@@ -104,19 +100,18 @@ func (c *commonConfig) CompileConfigs(req domain.CompileConfigsRequest) domain.C
return result return result
} }
// GetLinks godoc
// @Summary Метод получения связей общей конфигурациями с конфигурацией модулей // @Summary Метод получения связей общей конфигурациями с конфигурацией модулей
// @Description Возвращает ассоциативный массив, ключами которого являются название модулей, а значения - название конфигурации модуля // @Description Возвращает ассоциативный массив, ключами которого являются название модулей, а значения - название конфигурации модуля
// @Tags Общие конфигурации // @Tags Общие конфигурации
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param body body domain.ConfigIdRequest true "id общей конфигурации" // @Param body body domain.ConfigIdRequest true "id общей конфигурации"
// @Success 200 {object} domain.CommonConfigLinks // @Success 200 {object} domain.CommonConfigLinks
// @Router /common_config/get_links [POST] // @Router /common_config/get_links [POST]
func (c *commonConfig) GetLinks(req domain.ConfigIdRequest) domain.CommonConfigLinks { func (c *commonConfig) GetLinks(req domain.ConfigIdRequest) domain.CommonConfigLinks {
var result domain.CommonConfigLinks var result domain.CommonConfigLinks
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) { c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
result = service.CommonConfigService.GetCommonConfigLinks(req.Id, state) result = service.CommonConfig.GetCommonConfigLinks(req.Id, state)
}) })
return result return result
} }
+115 -18
View File
@@ -1,12 +1,15 @@
package controller package controller
import ( import (
"time"
"github.com/integration-system/isp-lib/v2/utils" "github.com/integration-system/isp-lib/v2/utils"
"google.golang.org/grpc/codes" "google.golang.org/grpc/codes"
"google.golang.org/grpc/status" "google.golang.org/grpc/status"
"isp-config-service/cluster" "isp-config-service/cluster"
"isp-config-service/domain" "isp-config-service/domain"
"isp-config-service/entity" "isp-config-service/entity"
"isp-config-service/service"
"isp-config-service/store" "isp-config-service/store"
"isp-config-service/store/state" "isp-config-service/store/state"
) )
@@ -17,12 +20,11 @@ type config struct {
rstore *store.Store rstore *store.Store
} }
// GetActiveConfigByModuleName godoc
// @Summary Метод получения объекта конфигурации по названию модуля // @Summary Метод получения объекта конфигурации по названию модуля
// @Description Возвращает активную конфиграцию по названию модуля // @Description Возвращает активную конфиграцию по названию модуля
// @Tags Конфигурация // @Tags Конфигурация
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param body body domain.GetByModuleNameRequest true "название модуля" // @Param body body domain.GetByModuleNameRequest true "название модуля"
// @Success 200 {object} entity.Config // @Success 200 {object} entity.Config
// @Failure 404 {object} structure.GrpcError "если конфигурация не найдена" // @Failure 404 {object} structure.GrpcError "если конфигурация не найдена"
@@ -48,13 +50,47 @@ func (c *config) GetActiveConfigByModuleName(request domain.GetByModuleNameReque
return config, nil 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 Метод обновления конфигурации // @Summary Метод обновления конфигурации
// @Description Если конфиг с таким id существует, то обновляет данные, если нет, то добавляет данные в базу // @Description Если конфиг с таким id существует, то обновляет данные, если нет, то добавляет данные в базу
// В случае обновления рассылает все подключенным модулям актуальную конфигурацию // @Description В случае обновления рассылает всем подключенным модулям актуальную конфигурацию
// @Tags Конфигурация // @Tags Конфигурация
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param body body domain.CreateUpdateConfigRequest true "объект для сохранения" // @Param body body domain.CreateUpdateConfigRequest true "объект для сохранения"
// @Success 200 {object} domain.ConfigModuleInfo // @Success 200 {object} domain.ConfigModuleInfo
// @Failure 404 {object} structure.GrpcError "если конфигурация не найдена" // @Failure 404 {object} structure.GrpcError "если конфигурация не найдена"
@@ -66,15 +102,17 @@ func (c *config) CreateUpdateConfig(config domain.CreateUpdateConfigRequest) (*d
config.CreatedAt = now config.CreatedAt = now
config.UpdatedAt = now config.UpdatedAt = now
upsertConfig := cluster.UpsertConfig{ upsertConfig := cluster.UpsertConfig{
Config: config.Config, Config: config.Config,
Unsafe: config.Unsafe, Unsafe: config.Unsafe,
VersionId: state.GenerateId(),
VersionCreateAt: time.Now(),
} }
if config.Id == "" { if config.Id == "" {
upsertConfig.Config.Id = state.GenerateId() upsertConfig.Config.Id = state.GenerateId()
upsertConfig.Create = true upsertConfig.Create = true
} }
command := cluster.PrepareUpsertConfigCommand(upsertConfig) command := cluster.PrepareUpsertConfigCommand(upsertConfig)
err := PerformSyncApplyWithError(command, "UpsertConfigCommand", &response) err := PerformSyncApplyWithError(command, &response)
if err != nil { if err != nil {
return nil, err return nil, err
} else if response.ErrorDetails != nil { } else if response.ErrorDetails != nil {
@@ -84,12 +122,11 @@ func (c *config) CreateUpdateConfig(config domain.CreateUpdateConfigRequest) (*d
return response.Config, nil return response.Config, nil
} }
// MarkConfigAsActive godoc
// @Summary Метод активации конфигурации для модуля // @Summary Метод активации конфигурации для модуля
// @Description Активирует указанную конфигурацию и деактивирует остальные, возвращает активированную конфигурацию // @Description Активирует указанную конфигурацию и деактивирует остальные, возвращает активированную конфигурацию
// @Tags Конфигурация // @Tags Конфигурация
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param body body domain.ConfigIdRequest true "id конфигурации для изменения" // @Param body body domain.ConfigIdRequest true "id конфигурации для изменения"
// @Success 200 {object} entity.Config "активированная конфигурация" // @Success 200 {object} entity.Config "активированная конфигурация"
// @Failure 404 {object} structure.GrpcError "если конфигурация не найдена" // @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) { func (c *config) MarkConfigAsActive(identity domain.ConfigIdRequest) (*entity.Config, error) {
var response entity.Config var response entity.Config
command := cluster.PrepareActivateConfigCommand(identity.Id, state.GenerateDate()) command := cluster.PrepareActivateConfigCommand(identity.Id, state.GenerateDate())
err := PerformSyncApplyWithError(command, "ActivateConfigCommand", &response) err := PerformSyncApplyWithError(command, &response)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &response, nil return &response, nil
} }
// DeleteConfigs godoc
// @Summary Метод удаления объектов конфигурации по идентификаторам // @Summary Метод удаления объектов конфигурации по идентификаторам
// @Description Возвращает количество удаленных модулей // @Description Возвращает количество удаленных модулей
// @Tags Конфигурация // @Tags Конфигурация
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param body body []string true "массив идентификаторов конфигураций" // @Param body body []string true "массив идентификаторов конфигураций"
// @Success 200 {object} domain.DeleteResponse // @Success 200 {object} domain.DeleteResponse
// @Failure 400 {object} structure.GrpcError "если не указан массив идентификаторов" // @Failure 400 {object} structure.GrpcError "если не указан массив идентификаторов"
@@ -125,13 +161,74 @@ func (c *config) DeleteConfigs(identities []string) (*domain.DeleteResponse, err
} }
var response domain.DeleteResponse var response domain.DeleteResponse
command := cluster.PrepareDeleteConfigsCommand(identities) command := cluster.PrepareDeleteConfigsCommand(identities)
err := PerformSyncApply(command, "DeleteConfigsCommand", &response) err := PerformSyncApply(command, &response)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &response, nil 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 { func NewConfig(rstore *store.Store) *config {
return &config{ return &config{
rstore: rstore, rstore: rstore,
+13 -7
View File
@@ -17,13 +17,15 @@ func unknownError() error {
return status.Error(codes.Unknown, utils.ServiceError) 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) applyLogResponse, err := holder.ClusterClient.SyncApply(command)
if err != nil { 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() return unknownError()
} }
if applyLogResponse != nil && applyLogResponse.ApplyError != "" { if applyLogResponse != nil && applyLogResponse.ApplyError != "" {
commandName := cluster.ParseCommand(command).String()
log.WithMetadata(map[string]interface{}{ log.WithMetadata(map[string]interface{}{
"result": string(applyLogResponse.Result), "result": string(applyLogResponse.Result),
"applyError": applyLogResponse.ApplyError, "applyError": applyLogResponse.ApplyError,
@@ -31,20 +33,24 @@ func PerformSyncApply(command []byte, commandName string, responsePtr interface{
}).Warnf(codes2.SyncApplyError, "apply command") }).Warnf(codes2.SyncApplyError, "apply command")
return unknownError() return unknownError()
} }
err = json.Unmarshal(applyLogResponse.Result, responsePtr) if responsePtr != nil {
if err != nil { err = json.Unmarshal(applyLogResponse.Result, responsePtr)
return unknownError() if err != nil {
return unknownError()
}
} }
return nil return nil
} }
func PerformSyncApplyWithError(command []byte, commandName string, responsePtr interface{}) error { func PerformSyncApplyWithError(command []byte, responsePtr interface{}) error {
applyLogResponse, err := holder.ClusterClient.SyncApply(command) applyLogResponse, err := holder.ClusterClient.SyncApply(command)
if err != nil { 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() return unknownError()
} }
if applyLogResponse != nil && applyLogResponse.ApplyError != "" { if applyLogResponse != nil && applyLogResponse.ApplyError != "" {
commandName := cluster.ParseCommand(command).String()
log.WithMetadata(map[string]interface{}{ log.WithMetadata(map[string]interface{}{
"result": string(applyLogResponse.Result), "result": string(applyLogResponse.Result),
"applyError": applyLogResponse.ApplyError, "applyError": applyLogResponse.ApplyError,
+31 -6
View File
@@ -8,18 +8,22 @@ import (
"isp-config-service/service" "isp-config-service/service"
"isp-config-service/store" "isp-config-service/store"
"isp-config-service/store/state" "isp-config-service/store/state"
"time"
"github.com/integration-system/isp-lib/v2/utils" "github.com/integration-system/isp-lib/v2/utils"
"google.golang.org/grpc/codes" "google.golang.org/grpc/codes"
) )
const (
defaultEventLifetime = 5 * time.Second
)
var Module *module var Module *module
type module struct { type module struct {
rstore *store.Store rstore *store.Store
} }
// GetModulesAggregatedInfo godoc
// @Summary Метод получения полной информации о состоянии модуля // @Summary Метод получения полной информации о состоянии модуля
// @Description Возвращает полное состояние всех модулей в кластере (конфигурация, схема конфигурации, подключенные экземпляры) // @Description Возвращает полное состояние всех модулей в кластере (конфигурация, схема конфигурации, подключенные экземпляры)
// @Tags Модули // @Tags Модули
@@ -31,12 +35,11 @@ type module struct {
func (c *module) GetModulesAggregatedInfo() ([]domain.ModuleInfo, error) { func (c *module) GetModulesAggregatedInfo() ([]domain.ModuleInfo, error) {
var response []domain.ModuleInfo var response []domain.ModuleInfo
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) { c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
response = service.ModuleRegistryService.GetAggregatedModuleInfo(state) response = service.ModuleRegistry.GetAggregatedModuleInfo(state)
}) })
return response, nil return response, nil
} }
// DeleteModules godoc
// @Summary Метод удаления объектов модулей по идентификаторам // @Summary Метод удаления объектов модулей по идентификаторам
// @Description Возвращает количество удаленных модулей // @Description Возвращает количество удаленных модулей
// @Tags Модули // @Tags Модули
@@ -56,16 +59,14 @@ func (*module) DeleteModules(identities []string) (*domain.DeleteResponse, error
var deleteResponse domain.DeleteResponse var deleteResponse domain.DeleteResponse
command := cluster.PrepareDeleteModulesCommand(identities) command := cluster.PrepareDeleteModulesCommand(identities)
err := PerformSyncApply(command, "DeleteCommonConfigsCommand", &deleteResponse) err := PerformSyncApply(command, &deleteResponse)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &deleteResponse, err return &deleteResponse, err
} }
// GetModuleByName godoc
// @Summary Метод получения модуля по имени // @Summary Метод получения модуля по имени
// @Description Модуль
// @Tags Модули // @Tags Модули
// @Accept json // @Accept json
// @Produce json // @Produce json
@@ -85,6 +86,30 @@ func (c *module) GetModuleByName(req domain.GetByModuleNameRequest) (*entity.Mod
return module, nil 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 { func NewModule(rstore *store.Store) *module {
return &module{ return &module{
rstore: rstore, rstore: rstore,
-1
View File
@@ -14,7 +14,6 @@ type routes struct {
rstore *store.Store rstore *store.Store
} }
// GetRoutes godoc
// @Summary Метод получения маршрутов // @Summary Метод получения маршрутов
// @Description Возвращает все доступные модули // @Description Возвращает все доступные модули
// @Tags Роуты // @Tags Роуты
+2 -3
View File
@@ -15,12 +15,11 @@ type schema struct {
rstore *store.Store rstore *store.Store
} }
// GetByModuleId godoc
// @Summary Метод получения схемы конфигурации модуля // @Summary Метод получения схемы конфигурации модуля
// @Description Возвращает текущую json схему конфигурации модуля // @Description Возвращает текущую json схему конфигурации модуля
// @Tags Схема // @Tags Схема
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param body body domain.GetByModuleIdRequest true "идентификатор модуля" // @Param body body domain.GetByModuleIdRequest true "идентификатор модуля"
// @Success 200 {object} entity.ConfigSchema // @Success 200 {object} entity.ConfigSchema
// @Failure 404 {object} structure.GrpcError "если схема для модуля не найдена" // @Failure 404 {object} structure.GrpcError "если схема для модуля не найдена"
+353 -176
View File
@@ -1,5 +1,18 @@
basePath: /api/config basePath: /api/config
definitions: definitions:
domain.BroadcastEventRequest:
properties:
event:
type: string
moduleNames:
items:
type: string
type: array
payload:
items:
type: integer
type: array
type: object
domain.CommonConfigLinks: domain.CommonConfigLinks:
additionalProperties: additionalProperties:
items: items:
@@ -23,8 +36,6 @@ definitions:
properties: properties:
id: id:
type: string type: string
required:
- id
type: object type: object
domain.ConfigModuleInfo: domain.ConfigModuleInfo:
properties: properties:
@@ -38,7 +49,6 @@ definitions:
type: string type: string
data: data:
$ref: '#/definitions/entity.ConfigData' $ref: '#/definitions/entity.ConfigData'
type: object
description: description:
type: string type: string
id: id:
@@ -53,15 +63,11 @@ definitions:
type: boolean type: boolean
version: version:
type: integer type: integer
required:
- moduleId
- name
type: object type: object
domain.Connection: domain.Connection:
properties: properties:
address: address:
$ref: '#/definitions/structure.AddressConfiguration' $ref: '#/definitions/structure.AddressConfiguration'
type: object
endpoints: endpoints:
items: items:
$ref: '#/definitions/structure.EndpointDescriptor' $ref: '#/definitions/structure.EndpointDescriptor'
@@ -85,7 +91,6 @@ definitions:
type: string type: string
data: data:
$ref: '#/definitions/entity.ConfigData' $ref: '#/definitions/entity.ConfigData'
type: object
description: description:
type: string type: string
id: id:
@@ -100,9 +105,6 @@ definitions:
type: string type: string
version: version:
type: integer type: integer
required:
- moduleId
- name
type: object type: object
domain.DeleteCommonConfigResponse: domain.DeleteCommonConfigResponse:
properties: properties:
@@ -110,7 +112,6 @@ definitions:
type: boolean type: boolean
links: links:
$ref: '#/definitions/domain.CommonConfigLinks' $ref: '#/definitions/domain.CommonConfigLinks'
type: object
type: object type: object
domain.DeleteResponse: domain.DeleteResponse:
properties: properties:
@@ -121,15 +122,20 @@ definitions:
properties: properties:
moduleId: moduleId:
type: string type: string
required:
- moduleId
type: object type: object
domain.GetByModuleNameRequest: domain.GetByModuleNameRequest:
properties: properties:
moduleName: moduleName:
type: string type: string
required: type: object
- moduleName domain.ModuleDependency:
properties:
id:
type: string
name:
type: string
required:
type: boolean
type: object type: object
domain.ModuleInfo: domain.ModuleInfo:
properties: properties:
@@ -137,7 +143,6 @@ definitions:
type: boolean type: boolean
configSchema: configSchema:
$ref: '#/definitions/schema.Schema' $ref: '#/definitions/schema.Schema'
type: object
configs: configs:
items: items:
$ref: '#/definitions/domain.ConfigModuleInfo' $ref: '#/definitions/domain.ConfigModuleInfo'
@@ -152,6 +157,10 @@ definitions:
type: string type: string
name: name:
type: string type: string
requiredModules:
items:
$ref: '#/definitions/domain.ModuleDependency'
type: array
status: status:
items: items:
$ref: '#/definitions/domain.Connection' $ref: '#/definitions/domain.Connection'
@@ -163,7 +172,6 @@ definitions:
type: string type: string
data: data:
$ref: '#/definitions/entity.ConfigData' $ref: '#/definitions/entity.ConfigData'
type: object
description: description:
type: string type: string
id: id:
@@ -172,8 +180,6 @@ definitions:
type: string type: string
updatedAt: updatedAt:
type: string type: string
required:
- name
type: object type: object
entity.Config: entity.Config:
properties: properties:
@@ -187,7 +193,6 @@ definitions:
type: string type: string
data: data:
$ref: '#/definitions/entity.ConfigData' $ref: '#/definitions/entity.ConfigData'
type: object
description: description:
type: string type: string
id: id:
@@ -200,9 +205,6 @@ definitions:
type: string type: string
version: version:
type: integer type: integer
required:
- moduleId
- name
type: object type: object
entity.ConfigData: entity.ConfigData:
additionalProperties: true additionalProperties: true
@@ -217,7 +219,6 @@ definitions:
type: string type: string
schema: schema:
$ref: '#/definitions/schema.Schema' $ref: '#/definitions/schema.Schema'
type: object
updatedAt: updatedAt:
type: string type: string
version: version:
@@ -235,137 +236,24 @@ definitions:
type: string type: string
name: name:
type: string type: string
required: type: object
- name entity.VersionConfig:
properties:
configId:
type: string
configVersion:
type: integer
createdAt:
type: string
data:
$ref: '#/definitions/entity.ConfigData'
id:
type: string
type: object type: object
jsonschema.Definitions: jsonschema.Definitions:
additionalProperties: additionalProperties:
$ref: '#/definitions/jsonschema.Type' $ref: '#/definitions/jsonschema.Type'
type: object 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: jsonschema.Type:
properties: properties:
$ref: $ref:
@@ -375,31 +263,33 @@ definitions:
description: RFC draft-wright-json-schema-00 description: RFC draft-wright-json-schema-00
type: string type: string
additionalItems: additionalItems:
allOf:
- $ref: '#/definitions/jsonschema.Type'
description: section 5.9 description: section 5.9
type: integer
additionalProperties: additionalProperties:
description: section 5.18 description: section 5.18
type: string items:
type: integer
type: array
allOf: allOf:
description: section 5.22 description: section 5.22
items: items:
type: integer $ref: '#/definitions/jsonschema.Type'
type: array type: array
anyOf: anyOf:
description: section 5.23 description: section 5.23
items: items:
type: integer $ref: '#/definitions/jsonschema.Type'
type: array type: array
binaryEncoding: binaryEncoding:
description: section 4.3 description: section 4.3
type: string type: string
default: default:
description: section 6.2 description: section 6.2
type: object
definitions: definitions:
$ref: '#/definitions/jsonschema.Definitions' allOf:
- $ref: '#/definitions/jsonschema.Definitions'
description: section 5.26 description: section 5.26
type: object
dependencies: dependencies:
additionalProperties: additionalProperties:
$ref: '#/definitions/jsonschema.Type' $ref: '#/definitions/jsonschema.Type'
@@ -410,8 +300,7 @@ definitions:
type: string type: string
enum: enum:
description: section 5.20 description: section 5.20
items: items: {}
type: object
type: array type: array
exclusiveMaximum: exclusiveMaximum:
description: section 5.3 description: section 5.3
@@ -423,8 +312,9 @@ definitions:
description: section 7 description: section 7
type: string type: string
items: items:
allOf:
- $ref: '#/definitions/jsonschema.Type'
description: section 5.9 description: section 5.9
type: integer
maxItems: maxItems:
description: section 5.10 description: section 5.10
type: integer type: integer
@@ -438,8 +328,9 @@ definitions:
description: section 5.2 description: section 5.2
type: integer type: integer
media: media:
allOf:
- $ref: '#/definitions/jsonschema.Type'
description: RFC draft-wright-json-schema-hyperschema-00, section 4 description: RFC draft-wright-json-schema-hyperschema-00, section 4
type: integer
minItems: minItems:
description: section 5.11 description: section 5.11
type: integer type: integer
@@ -456,12 +347,13 @@ definitions:
description: RFC draft-wright-json-schema-validation-00, section 5 description: RFC draft-wright-json-schema-validation-00, section 5
type: integer type: integer
not: not:
allOf:
- $ref: '#/definitions/jsonschema.Type'
description: section 5.25 description: section 5.25
type: integer
oneOf: oneOf:
description: section 5.24 description: section 5.24
items: items:
type: integer $ref: '#/definitions/jsonschema.Type'
type: array type: array
pattern: pattern:
description: section 5.8 description: section 5.8
@@ -492,7 +384,132 @@ definitions:
type: boolean type: boolean
type: object type: object
schema.Schema: 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: structure.AddressConfiguration:
properties: properties:
ip: ip:
@@ -504,7 +521,6 @@ definitions:
properties: properties:
address: address:
$ref: '#/definitions/structure.AddressConfiguration' $ref: '#/definitions/structure.AddressConfiguration'
type: object
endpoints: endpoints:
items: items:
$ref: '#/definitions/structure.EndpointDescriptor' $ref: '#/definitions/structure.EndpointDescriptor'
@@ -513,6 +529,10 @@ definitions:
type: string type: string
moduleName: moduleName:
type: string type: string
requiredModules:
items:
$ref: '#/definitions/structure.ModuleDependency'
type: array
version: version:
type: string type: string
type: object type: object
@@ -527,20 +547,24 @@ definitions:
type: string type: string
userAuthRequired: userAuthRequired:
type: boolean type: boolean
required:
- path
type: object type: object
structure.GrpcError: structure.GrpcError:
properties: properties:
details: details:
items: items: {}
type: object
type: array type: array
errorCode: errorCode:
type: string type: string
errorMessage: errorMessage:
type: string type: string
type: object type: object
structure.ModuleDependency:
properties:
name:
type: string
required:
type: boolean
type: object
host: localhost:9003 host: localhost:9003
info: info:
contact: {} contact: {}
@@ -548,7 +572,7 @@ info:
license: license:
name: GNU GPL v3.0 name: GNU GPL v3.0
title: ISP configuration service title: ISP configuration service
version: 2.0.0 version: 2.4.1
paths: paths:
/common_config/compile: /common_config/compile:
post: post:
@@ -576,8 +600,9 @@ paths:
post: post:
consumes: consumes:
- application/json - application/json
description: Если конфиг с таким id существует, то обновляет данные, если нет, description: |-
то добавляет данные в базу Если конфиг с таким id существует, то обновляет данные, если нет, то добавляет данные в базу
В случае обновления рассылает всем подключенным модулям актуальную конфигурацию
parameters: parameters:
- description: объект для сохранения - description: объект для сохранения
in: body in: body
@@ -675,8 +700,9 @@ paths:
post: post:
consumes: consumes:
- application/json - application/json
description: Если конфиг с таким id существует, то обновляет данные, если нет, description: |-
то добавляет данные в базу Если конфиг с таким id существует, то обновляет данные, если нет, то добавляет данные в базу
В случае обновления рассылает всем подключенным модулям актуальную конфигурацию
parameters: parameters:
- description: объект для сохранения - description: объект для сохранения
in: body in: body
@@ -734,6 +760,36 @@ paths:
summary: Метод удаления объектов конфигурации по идентификаторам summary: Метод удаления объектов конфигурации по идентификаторам
tags: 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: /config/get_active_config_by_module_name:
post: post:
consumes: consumes:
@@ -764,6 +820,105 @@ paths:
summary: Метод получения объекта конфигурации по названию модуля summary: Метод получения объекта конфигурации по названию модуля
tags: 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: /config/mark_config_as_active:
post: post:
consumes: consumes:
@@ -795,6 +950,29 @@ paths:
summary: Метод активации конфигурации для модуля summary: Метод активации конфигурации для модуля
tags: 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: /module/delete_module:
post: post:
consumes: consumes:
@@ -827,7 +1005,6 @@ paths:
post: post:
consumes: consumes:
- application/json - application/json
description: Модуль
parameters: parameters:
- description: название модуля - description: название модуля
in: body in: body
+11 -1
View File
@@ -1,6 +1,10 @@
package domain package domain
import "isp-config-service/entity" import (
json2 "encoding/json"
"isp-config-service/entity"
)
type ConfigIdRequest struct { type ConfigIdRequest struct {
Id string `json:"id" valid:"required~Required"` Id string `json:"id" valid:"required~Required"`
@@ -19,6 +23,12 @@ type GetByModuleNameRequest struct {
ModuleName string `valid:"required~Required"` ModuleName string `valid:"required~Required"`
} }
type BroadcastEventRequest struct {
ModuleNames []string `valid:"required~Required"`
Event string `valid:"required~Required"`
Payload json2.RawMessage
}
type CreateUpdateConfigRequest struct { type CreateUpdateConfigRequest struct {
entity.Config entity.Config
Unsafe bool Unsafe bool
+11 -4
View File
@@ -19,19 +19,26 @@ type ModuleInfo struct {
CreatedAt time.Time CreatedAt time.Time
LastConnectedAt time.Time LastConnectedAt time.Time
LastDisconnectedAt time.Time LastDisconnectedAt time.Time
Configs []ConfigModuleInfo `json:",omitempty"` Configs []ConfigModuleInfo
ConfigSchema *schema.Schema `json:",omitempty"` ConfigSchema *schema.Schema
Status []Connection `json:",omitempty"` Status []Connection
RequiredModules []ModuleDependency
} }
type Connection struct { type Connection struct {
LibVersion string LibVersion string
Version string Version string
Address structure.AddressConfiguration Address structure.AddressConfiguration
Endpoints []structure.EndpointDescriptor `json:",omitempty"` Endpoints []structure.EndpointDescriptor
EstablishedAt time.Time EstablishedAt time.Time
} }
type ModuleDependency struct {
Id string
Name string
Required bool
}
type CommonConfigLinks map[string][]string type CommonConfigLinks map[string][]string
type CompiledConfigResponse map[string]interface{} type CompiledConfigResponse map[string]interface{}
+11 -11
View File
@@ -10,33 +10,33 @@ type ConfigData map[string]interface{}
type Config struct { type Config struct {
//nolint //nolint
tableName string `sql:"?db_schema.configs" json:"-"` tableName string `pg:"?db_schema.configs" json:"-"`
Id string `json:"id"` Id string `json:"id"`
Name string `json:"name" valid:"required~Required"` Name string `json:"name" valid:"required~Required"`
CommonConfigs []string `json:"commonConfigs" pg:",array"` CommonConfigs []string `json:"commonConfigs" pg:",array"`
Description string `json:"description"` Description string `json:"description"`
ModuleId string `json:"moduleId" valid:"required~Required"` ModuleId string `json:"moduleId" valid:"required~Required"`
Version int32 `json:"version" sql:",null"` Version int32 `json:"version" pg:",null"`
Active bool `json:"active" sql:",null"` Active bool `json:"active" pg:",null"`
CreatedAt time.Time `json:"createdAt" sql:",null"` CreatedAt time.Time `json:"createdAt" pg:",null"`
UpdatedAt time.Time `json:"updatedAt" sql:",null"` UpdatedAt time.Time `json:"updatedAt" pg:",null"`
Data ConfigData `json:"data" sql:",notnull"` Data ConfigData `json:"data,omitempty" pg:",notnull"`
} }
type CommonConfig struct { type CommonConfig struct {
//nolint //nolint
tableName string `sql:"?db_schema.common_configs" json:"-"` tableName string `pg:"?db_schema.common_configs" json:"-"`
Id string `json:"id"` Id string `json:"id"`
Name string `json:"name" valid:"required~Required"` Name string `json:"name" valid:"required~Required"`
Description string `json:"description"` Description string `json:"description"`
CreatedAt time.Time `json:"createdAt" sql:",null"` CreatedAt time.Time `json:"createdAt" pg:",null"`
UpdatedAt time.Time `json:"updatedAt" sql:",null"` UpdatedAt time.Time `json:"updatedAt" pg:",null"`
Data ConfigData `json:"data" sql:",notnull"` Data ConfigData `json:"data" pg:",notnull"`
} }
type ConfigSchema struct { type ConfigSchema struct {
//nolint //nolint
tableName string `sql:"?db_schema.config_schemas" json:"-"` tableName string `pg:"?db_schema.config_schemas" json:"-"`
Id string `json:"id"` Id string `json:"id"`
Version string Version string
ModuleId string ModuleId string
+2 -2
View File
@@ -4,10 +4,10 @@ import "time"
type Module struct { type Module struct {
//nolint //nolint
tableName string `sql:"?db_schema.modules" json:"-"` tableName string `pg:"?db_schema.modules" json:"-"`
Id string `json:"id"` Id string `json:"id"`
Name string `json:"name" valid:"required~Required"` 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"` LastConnectedAt time.Time `json:"lastConnectedAt"`
LastDisconnectedAt time.Time `json:"lastDisconnectedAt"` LastDisconnectedAt time.Time `json:"lastDisconnectedAt"`
} }
+15
View File
@@ -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
}
+93 -16
View File
@@ -1,25 +1,102 @@
module isp-config-service module isp-config-service
go 1.13 go 1.19
require ( require (
github.com/asaskevich/govalidator v0.0.0-20180315120708-ccb8e960c48f github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d
github.com/cenkalti/backoff/v4 v4.0.0 github.com/cenkalti/backoff/v4 v4.2.0
github.com/go-pg/pg/v9 v9.1.3 github.com/go-pg/pg/v9 v9.2.1
github.com/hashicorp/raft v1.1.2 github.com/hashicorp/raft v1.3.11
github.com/hashicorp/raft-boltdb v0.0.0-20191021154308-4207f1bf0617 github.com/hashicorp/raft-boltdb/v2 v2.2.2
github.com/integration-system/bellows v0.0.0-20190821124023-244325e8836c github.com/integration-system/bellows v1.0.1
github.com/integration-system/isp-etp-go/v2 v2.1.0 github.com/integration-system/isp-etp-go/v2 v2.1.3
github.com/integration-system/isp-lib-test v1.5.0 github.com/integration-system/isp-lib/v2 v2.11.0
github.com/integration-system/isp-lib/v2 v2.2.0 github.com/integration-system/isp-log v1.2.0
github.com/integration-system/isp-log v1.1.2 github.com/integration-system/net-mux v1.0.1
github.com/integration-system/net-mux v1.0.0 github.com/json-iterator/go v1.1.12
github.com/json-iterator/go v1.1.9
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826
github.com/pkg/errors v0.9.1 github.com/pkg/errors v0.9.1
github.com/satori/go.uuid v1.2.0 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 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
) )
+682 -233
View File
File diff suppressed because it is too large. Load diff
+12 -1
View File
@@ -1,4 +1,4 @@
//nolint lll //nolint:lll
package helper package helper
import ( import (
@@ -13,11 +13,17 @@ type Handlers struct {
DeleteModules func(identities []string) (*domain.DeleteResponse, error) `method:"delete_module" group:"module" inner:"true"` DeleteModules func(identities []string) (*domain.DeleteResponse, error) `method:"delete_module" group:"module" inner:"true"`
GetModulesInfo func() ([]domain.ModuleInfo, error) `method:"get_modules_info" group:"module" inner:"true"` GetModulesInfo func() ([]domain.ModuleInfo, error) `method:"get_modules_info" group:"module" inner:"true"`
GetModuleByName func(req domain.GetByModuleNameRequest) (*entity.Module, error) `method:"get_by_name" group:"module" inner:"true"` 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 ===== // ===== CONFIG =====
GetActiveConfigByModuleName func(request domain.GetByModuleNameRequest) (*entity.Config, error) `method:"get_active_config_by_module_name" group:"config" inner:"true"` GetActiveConfigByModuleName func(request domain.GetByModuleNameRequest) (*entity.Config, error) `method:"get_active_config_by_module_name" group:"config" inner:"true"`
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"` 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"` 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"` 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 ===== // ===== COMMON CONFIG =====
GetCommonConfigs func(identities []string) []entity.CommonConfig `method:"get_configs" group:"common_config" inner:"true"` 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, DeleteModules: controller.Module.DeleteModules,
GetModulesInfo: controller.Module.GetModulesAggregatedInfo, GetModulesInfo: controller.Module.GetModulesAggregatedInfo,
GetModuleByName: controller.Module.GetModuleByName, GetModuleByName: controller.Module.GetModuleByName,
BroadcastEvent: controller.Module.BroadcastEvent,
GetActiveConfigByModuleName: controller.Config.GetActiveConfigByModuleName, GetActiveConfigByModuleName: controller.Config.GetActiveConfigByModuleName,
GetConfigsByModuleId: controller.Config.GetConfigsByModuleId,
CreateUpdateConfig: controller.Config.CreateUpdateConfig, CreateUpdateConfig: controller.Config.CreateUpdateConfig,
MarkConfigAsActive: controller.Config.MarkConfigAsActive, MarkConfigAsActive: controller.Config.MarkConfigAsActive,
DeleteConfig: controller.Config.DeleteConfigs, DeleteConfig: controller.Config.DeleteConfigs,
DeleteVersion: controller.Config.DeleteConfigVersion,
GetAllVersion: controller.Config.GetAllVersion,
GetConfigByID: controller.Config.GetConfigById,
GetCommonConfigs: controller.CommonConfig.GetConfigs, GetCommonConfigs: controller.CommonConfig.GetConfigs,
CreateUpdateCommonConfig: controller.CommonConfig.CreateUpdateConfig, CreateUpdateCommonConfig: controller.CommonConfig.CreateUpdateConfig,
+54 -20
View File
@@ -6,16 +6,19 @@ import (
"net" "net"
"net/http" "net/http"
"os" "os"
"os/signal"
"syscall"
"time"
"github.com/integration-system/isp-etp-go/v2" "github.com/integration-system/isp-etp-go/v2"
"github.com/integration-system/isp-lib/v2/backend" "github.com/integration-system/isp-lib/v2/backend"
"github.com/integration-system/isp-lib/v2/bootstrap" "github.com/integration-system/isp-lib/v2/bootstrap"
"github.com/integration-system/isp-lib/v2/config" "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/structure"
"github.com/integration-system/isp-lib/v2/utils" "github.com/integration-system/isp-lib/v2/utils"
log "github.com/integration-system/isp-log" log "github.com/integration-system/isp-log"
mux "github.com/integration-system/net-mux" mux "github.com/integration-system/net-mux"
"github.com/thecodeteam/goodbye"
"isp-config-service/cluster" "isp-config-service/cluster"
"isp-config-service/codes" "isp-config-service/codes"
"isp-config-service/conf" "isp-config-service/conf"
@@ -38,8 +41,7 @@ const (
var ( var (
version = "0.1.0" version = "0.1.0"
shutdownChan = make(chan struct{}) muxer mux.Mux
muxer mux.Mux
) )
func init() { func init() {
@@ -50,7 +52,7 @@ func init() {
} }
// @title ISP configuration service // @title ISP configuration service
// @version 2.0.0 // @version 2.4.1
// @description Сервис управления конфигурацией модулей ISP кластера // @description Сервис управления конфигурацией модулей ISP кластера
// @license.name GNU GPL v3.0 // @license.name GNU GPL v3.0
@@ -58,10 +60,9 @@ func init() {
// @host localhost:9003 // @host localhost:9003
// @BasePath /api/config // @BasePath /api/config
//go:generate swag init --parseVendor //go:generate swag init --parseDependency
//go:generate rm -f docs/docs.go docs/swagger.json //go:generate rm -f docs/swagger.json
func main() { func main() {
ctx := context.Background()
cfg := config.Get().(*conf.Configuration) cfg := config.Get().(*conf.Configuration)
handlers := helper.GetHandlers() handlers := helper.GetHandlers()
endpoints := backend.GetEndpoints(cfg.ModuleName, handlers) endpoints := backend.GetEndpoints(cfg.ModuleName, handlers)
@@ -83,11 +84,12 @@ func main() {
connectionReadLimit := defaultWsConnectionReadLimit connectionReadLimit := defaultWsConnectionReadLimit
if cfg.WS.WsConnectionReadLimitKB > 0 { if cfg.WS.WsConnectionReadLimitKB > 0 {
//nolint gomnd //nolint:gomnd
connectionReadLimit = cfg.WS.WsConnectionReadLimitKB << 10 connectionReadLimit = cfg.WS.WsConnectionReadLimitKB << 10
} }
cluster.WsConnectionReadLimit = connectionReadLimit cluster.WsConnectionReadLimit = connectionReadLimit
cfg.Database.Password = fmt.Sprintf("%s%s", cfg.Database.Password, os.Getenv("DB_PASSPART"))
model.DbClient.ReceiveConfiguration(cfg.Database) model.DbClient.ReceiveConfiguration(cfg.Database)
httpListener, raftListener, err := initMultiplexer(cfg.WS.Rest) httpListener, raftListener, err := initMultiplexer(cfg.WS.Rest)
@@ -96,14 +98,14 @@ func main() {
} }
_, raftStore := initRaft(raftListener, cfg.Cluster, declaration) _, raftStore := initRaft(raftListener, cfg.Cluster, declaration)
initWebsocket(ctx, connectionReadLimit, httpListener, raftStore) initWebsocket(connectionReadLimit, httpListener, raftStore)
initGrpc(cfg.WS.Grpc, raftStore) initGrpc(cfg.WS.Grpc, raftStore)
defer goodbye.Exit(ctx, -1) metric.InitProfiling(cfg.ModuleName)
goodbye.Notify(ctx) metric.InitCollectors(cfg.Metrics, structure.MetricConfiguration{})
goodbye.Register(onShutdown) metric.InitHttpServer(cfg.Metrics)
<-shutdownChan gracefulShutdown()
} }
func initMultiplexer(addressConfiguration structure.AddressConfiguration) (net.Listener, net.Listener, error) { 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 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{ etpConfig := etp.ServerConfig{
InsecureSkipVerify: true, InsecureSkipVerify: true,
ConnectionReadLimit: connectionReadLimit, ConnectionReadLimit: connectionReadLimit,
} }
etpServer := etp.NewServer(ctx, etpConfig) etpServer := etp.NewServer(context.Background(), etpConfig)
subs.NewSocketEventHandler(etpServer, raftStore).SubscribeAll() subs.NewSocketEventHandler(etpServer, raftStore).SubscribeAll()
mux := http.NewServeMux() mux := http.NewServeMux()
@@ -162,7 +164,7 @@ func initRaft(listener net.Listener, clusterCfg conf.ClusterConfiguration,
return nil, nil return nil, nil
} }
clusterClient := cluster.NewRaftClusterClient(r, declaration, func(address string) { 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) cfg := config.Get().(*conf.Configuration)
addr, err := net.ResolveTCPAddr("tcp", address) addr, err := net.ResolveTCPAddr("tcp", address)
if err != nil { if err != nil {
@@ -173,7 +175,7 @@ func initRaft(listener net.Listener, clusterCfg conf.ClusterConfiguration,
back := structure.BackendDeclaration{ModuleName: cfg.ModuleName, Address: addressConfiguration} back := structure.BackendDeclaration{ModuleName: cfg.ModuleName, Address: addressConfiguration}
log.WithMetadata(map[string]interface{}{"declaration": back}). log.WithMetadata(map[string]interface{}{"declaration": back}).
Infof(codes.LeaderManualDeleteLeader, "manually delete disconnected leader's declaration") Infof(codes.LeaderManualDeleteLeader, "manually delete disconnected leader's declaration")
service.ClusterMeshService.HandleDeleteBackendDeclarationCommand(back, s) service.ClusterMesh.HandleDeleteBackendDeclarationCommand(back, s)
}) })
}) })
holder.ClusterClient = clusterClient holder.ClusterClient = clusterClient
@@ -197,17 +199,45 @@ func initGrpc(bindAddress structure.AddressConfiguration, raftStore *store.Store
backend.StartBackendGrpcServer(bindAddress, defaultService) backend.StartBackendGrpcServer(bindAddress, defaultService)
} }
func onShutdown(ctx context.Context, _ os.Signal) { func gracefulShutdown() {
defer close(shutdownChan) 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() backend.StopGrpcServer()
holder.EtpServer.Close()
if err := holder.HTTPServer.Shutdown(ctx); err != nil { if err := holder.HTTPServer.Shutdown(ctx); err != nil {
log.Warnf(codes.ShutdownHttpServerError, "http server shutdown err: %v", err) log.Warnf(codes.ShutdownHttpServerError, "http server shutdown err: %v", err)
} else { } else {
log.Info(codes.ShutdownHttpServerInfo, "http server shutdown success") log.Info(codes.ShutdownHttpServerInfo, "http server shutdown success")
} }
holder.EtpServer.Close()
if err := holder.ClusterClient.Shutdown(); err != nil { if err := holder.ClusterClient.Shutdown(); err != nil {
log.Warnf(codes.RaftShutdownError, "raft shutdown err: %v", err) 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") log.Info(codes.RaftShutdownInfo, "raft shutdown success")
} }
if err := model.DbClient.Close(); err != nil {
log.Warnf(0, "database shutdown err: %v", err)
}
_ = muxer.Close() _ = 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
View File
@@ -15,8 +15,9 @@ var (
log.Fatal(stdcodes.InitializingDbError, err.Error()) log.Fatal(stdcodes.InitializingDbError, err.Error())
}), }),
) )
ConfigRep ConfigRepository = &configRepPg{rxClient: DbClient} ConfigRep ConfigRepository = &configRepPg{rxClient: DbClient}
CommonConfigRep CommonConfigRepository = &commonConfigRepPg{rxClient: DbClient} CommonConfigRep CommonConfigRepository = &commonConfigRepPg{rxClient: DbClient}
SchemaRep SchemaRepository = &schemaRepPg{rxClient: DbClient} SchemaRep SchemaRepository = &schemaRepPg{rxClient: DbClient}
ModuleRep ModulesRepository = &modulesRepPg{rxClient: DbClient} ModuleRep ModulesRepository = &modulesRepPg{rxClient: DbClient}
VersionStoreRep VersionConfigRepository = &versionConfigRepPg{rxClient: DbClient}
) )
+1 -1
View File
@@ -1,4 +1,4 @@
//nolint dupl //nolint: dupl
package model package model
import ( import (
+1 -1
View File
@@ -1,4 +1,4 @@
//nolint dupl //nolint:dupl
package model package model
import ( import (
+1 -1
View File
@@ -1,4 +1,4 @@
//nolint dupl //nolint:dupl
package model package model
import ( import (
+1 -1
View File
@@ -1,4 +1,4 @@
//nolint dupl //nolint:dupl
package model package model
import ( import (
+53
View File
@@ -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
View File
@@ -7,7 +7,7 @@ import (
"time" "time"
"github.com/hashicorp/raft" "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/integration-system/isp-log/adapter"
"github.com/pkg/errors" "github.com/pkg/errors"
"isp-config-service/codes" "isp-config-service/codes"
+5 -5
View File
@@ -6,7 +6,7 @@ import (
) )
var ( var (
ClusterMeshService clusterMeshService ClusterMesh clusterMeshService
) )
type clusterMeshService struct{} type clusterMeshService struct{}
@@ -14,15 +14,15 @@ type clusterMeshService struct{}
func (clusterMeshService) HandleUpdateBackendDeclarationCommand(declaration structure.BackendDeclaration, state state.WritableState) { func (clusterMeshService) HandleUpdateBackendDeclarationCommand(declaration structure.BackendDeclaration, state state.WritableState) {
changed := state.WritableMesh().UpsertBackend(declaration) changed := state.WritableMesh().UpsertBackend(declaration)
if changed { if changed {
DiscoveryService.BroadcastModuleAddresses(declaration.ModuleName, state.Mesh()) Discovery.BroadcastModuleAddresses(declaration.ModuleName, state.Mesh())
RoutesService.BroadcastRoutes(state.Mesh()) Routes.BroadcastRoutes(state.Mesh())
} }
} }
func (clusterMeshService) HandleDeleteBackendDeclarationCommand(declaration structure.BackendDeclaration, state state.WritableState) { func (clusterMeshService) HandleDeleteBackendDeclarationCommand(declaration structure.BackendDeclaration, state state.WritableState) {
deleted := state.WritableMesh().DeleteBackend(declaration) deleted := state.WritableMesh().DeleteBackend(declaration)
if deleted { if deleted {
DiscoveryService.BroadcastModuleAddresses(declaration.ModuleName, state.Mesh()) Discovery.BroadcastModuleAddresses(declaration.ModuleName, state.Mesh())
RoutesService.BroadcastRoutes(state.Mesh()) Routes.BroadcastRoutes(state.Mesh())
} }
} }
+2 -2
View File
@@ -12,7 +12,7 @@ import (
) )
var ( var (
CommonConfigService = commonConfigService{} CommonConfig = commonConfigService{}
) )
type commonConfigService struct{} type commonConfigService struct{}
@@ -72,7 +72,7 @@ func (s commonConfigService) HandleUpsertConfigCommand(
} }
if !upsertConfig.Create { if !upsertConfig.Create {
configsToBroadcast := state.Configs().FilterByCommonConfigs([]string{config.Id}) configsToBroadcast := state.Configs().FilterByCommonConfigs([]string{config.Id})
ConfigService.BroadcastNewConfig(state, configsToBroadcast...) ConfigService.BroadcastActiveConfigs(state, configsToBroadcast...)
} }
return cluster.NewResponse(config) return cluster.NewResponse(config)
} }
+29 -15
View File
@@ -23,8 +23,6 @@ var (
ConfigService = configService{} ConfigService = configService{}
) )
const ConfigWatchersRoomSuffix = "_config"
type configService struct{} type configService struct{}
type validationSchemaError struct { type validationSchemaError struct {
@@ -64,7 +62,7 @@ func (configService) CompileConfig(
return mergeNestedMaps(configsToMerge...) return mergeNestedMaps(configsToMerge...)
} }
func (configService) HandleActivateConfigCommand( func (cs configService) HandleActivateConfigCommand(
activateConfig cluster.ActivateConfig, state state.WritableState) cluster.ResponseWithError { activateConfig cluster.ActivateConfig, state state.WritableState) cluster.ResponseWithError {
configs := state.Configs().GetByIds([]string{activateConfig.ConfigId}) configs := state.Configs().GetByIds([]string{activateConfig.ConfigId})
if len(configs) == 0 { 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 { func (configService) HandleDeleteConfigsCommand(deleteConfigs cluster.DeleteConfigs, state state.WritableState) int {
@@ -101,7 +101,8 @@ func (configService) HandleDeleteConfigsCommand(deleteConfigs cluster.DeleteConf
return deleted 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 config := upsertConfig.Config
module := state.Modules().GetById(config.ModuleId) module := state.Modules().GetById(config.ModuleId)
if module == nil { if module == nil {
@@ -136,8 +137,13 @@ func (cs configService) HandleUpsertConfigCommand(upsertConfig cluster.UpsertCon
if len(configs) == 0 { if len(configs) == 0 {
return cluster.NewResponseErrorf(codes2.NotFound, "config with id %s not found", config.Id) 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) state.WritableConfigs().UpdateById(config)
ConfigHistory.SaveConfigVersion(upsertConfig.VersionId, oldCfg, state, upsertConfig.VersionCreateAt)
} }
if holder.ClusterClient.IsLeader() { if holder.ClusterClient.IsLeader() {
@@ -149,7 +155,8 @@ func (cs configService) HandleUpsertConfigCommand(upsertConfig cluster.UpsertCon
}).Errorf(codes.DatabaseOperationError, "upsert config: %v", err) }).Errorf(codes.DatabaseOperationError, "upsert config: %v", err)
} }
} }
cs.BroadcastNewConfig(state, config)
cs.BroadcastActiveConfigs(state, config)
return cluster.NewResponse(domain.CreateUpdateConfigResponse{ return cluster.NewResponse(domain.CreateUpdateConfigResponse{
Config: &domain.ConfigModuleInfo{ Config: &domain.ConfigModuleInfo{
Config: config, 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 { for i := range configs {
moduleID := configs[i].ModuleId cfg := &configs[i]
if !cfg.Active {
continue
}
moduleID := cfg.ModuleId
module := state.Modules().GetById(moduleID) module := state.Modules().GetById(moduleID)
moduleName := module.Name moduleName := module.Name
room := moduleName + ConfigWatchersRoomSuffix room := Room.Module(moduleName)
compiledConfig, err := cs.GetCompiledConfig(moduleName, state) compiledConfig, err := cs.GetCompiledConfig(moduleName, state)
if err != nil { if err != nil {
@@ -176,14 +187,17 @@ func (cs configService) BroadcastNewConfig(state state.ReadonlyState, configs ..
go cs.broadcast(room, utils.ConfigError, []byte(err.Error())) go cs.broadcast(room, utils.ConfigError, []byte(err.Error()))
continue continue
} }
go cs.broadcast(room, utils.ConfigSendConfigWhenConnected, data) go cs.broadcast(room, utils.ConfigSendConfigChanged, data)
} }
} }
func (cs configService) broadcast(room, event string, data []byte) { func (cs configService) broadcast(room, event string, body []byte) {
err := holder.EtpServer.BroadcastToRoom(room, utils.ConfigSendConfigWhenConnected, data) conns := holder.EtpServer.Rooms().ToBroadcast(room)
if err != nil { for _, conn := range conns {
log.Errorf(codes.ConfigServiceBroadcastConfigError, "broadcast %s err: %v", event, err) err := EmitConnWithTimeout(conn, event, body)
if err != nil {
log.Errorf(codes.ConfigServiceBroadcastConfigError, "broadcast '%s' to %s: %v", event, conn.RemoteAddr(), err)
}
} }
} }
-37
View File
@@ -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
View File
@@ -1,28 +1,27 @@
package service package service
import ( import (
"context"
"encoding/json" "encoding/json"
"sync" "sync"
"time"
"github.com/cenkalti/backoff/v4"
etp "github.com/integration-system/isp-etp-go/v2" etp "github.com/integration-system/isp-etp-go/v2"
"github.com/integration-system/isp-lib/v2/structure" "github.com/integration-system/isp-lib/v2/structure"
"github.com/integration-system/isp-lib/v2/utils" "github.com/integration-system/isp-lib/v2/utils"
log "github.com/integration-system/isp-log" log "github.com/integration-system/isp-log"
"isp-config-service/cluster"
"isp-config-service/codes" "isp-config-service/codes"
"isp-config-service/holder" "isp-config-service/holder"
"isp-config-service/store/state" "isp-config-service/store/state"
) )
const ( const (
messagesBackoffInterval = 100 * time.Millisecond AllModules = "*"
messagesBackoffMaxRetries = 3
) )
var ( var (
DiscoveryService = NewDiscoveryService() Discovery = &discoveryService{
subs: make(map[string][]string),
}
) )
type discoveryService struct { type discoveryService struct {
@@ -33,8 +32,8 @@ type discoveryService struct {
func (ds *discoveryService) HandleDisconnect(connID string) { func (ds *discoveryService) HandleDisconnect(connID string) {
ds.lock.Lock() ds.lock.Lock()
defer ds.lock.Unlock() defer ds.lock.Unlock()
if events, ok := ds.subs[connID]; ok { if rooms, ok := ds.subs[connID]; ok {
holder.EtpServer.Rooms().LeaveByConnId(connID, events...) holder.EtpServer.Rooms().LeaveByConnId(connID, rooms...)
delete(ds.subs, connID) delete(ds.subs, connID)
} }
} }
@@ -46,70 +45,91 @@ func (ds *discoveryService) Subscribe(conn etp.Conn, modules []string, mesh stat
ds.lock.Lock() ds.lock.Lock()
defer ds.lock.Unlock() defer ds.lock.Unlock()
eventsAddresses := make([][]structure.AddressConfiguration, 0, len(modules)) eventsAddresses := make([][]structure.AddressConfiguration, 0, len(modules))
events := make([]string, 0, len(modules)) rooms := make([]string, 0, len(modules))
for _, module := range modules { for _, module := range modules {
event := utils.ModuleConnected(module) room := Room.AddressListener(module)
addressList := mesh.GetModuleAddresses(module) addressList := mesh.GetModuleAddresses(module)
eventsAddresses = append(eventsAddresses, addressList) eventsAddresses = append(eventsAddresses, addressList)
events = append(events, event) rooms = append(rooms, room)
} }
ds.subs[conn.ID()] = events ds.subs[conn.ID()] = rooms
holder.EtpServer.Rooms().Join(conn, events...) holder.EtpServer.Rooms().Join(conn, rooms...)
go func(events []string, eventsAddresses [][]structure.AddressConfiguration, conn etp.Conn) { go func(events []string, eventsAddresses [][]structure.AddressConfiguration, conn etp.Conn) {
for i := range events { for i := range events {
event := events[i] event := events[i]
addressList := eventsAddresses[i] addressList := eventsAddresses[i]
err := ds.sendAddrList(conn, event, addressList) body, err := json.Marshal(addressList)
if err != nil { 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) { func (ds *discoveryService) BroadcastModuleAddresses(moduleName string, mesh state.ReadonlyMesh) {
ds.lock.RLock() ds.lock.RLock()
defer ds.lock.RUnlock() defer ds.lock.RUnlock()
room := Room.AddressListener(moduleName)
event := utils.ModuleConnected(moduleName) event := utils.ModuleConnected(moduleName)
addressList := mesh.GetModuleAddresses(moduleName) addressList := mesh.GetModuleAddresses(moduleName)
go func(room, event string, addressList []structure.AddressConfiguration) { go ds.broadcastModuleAddrList(room, event, addressList)
err := ds.broadcastAddrList(room, event, addressList) }
if err != nil {
log.Errorf(codes.DiscoveryServiceSendModulesError, "broadcast module connected %v", err) 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 { func (ds *discoveryService) broadcastModuleAddrList(room string, event string, addressList []structure.AddressConfiguration) {
bytes, err := json.Marshal(addressList) body, err := json.Marshal(addressList)
if err != nil { if err != nil {
return err panic(err)
} }
err = holder.EtpServer.BroadcastToRoom(room, event, bytes) conns := holder.EtpServer.Rooms().ToBroadcast(room)
if err != nil { for _, conn := range conns {
return err err := EmitConnWithTimeout(conn, event, body)
} if err != nil {
return nil log.Errorf(codes.DiscoveryServiceSendModulesError, "broadcast module connected to %s: %v", conn.RemoteAddr(), err)
} }
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),
} }
} }
+37 -5
View File
@@ -15,7 +15,7 @@ import (
) )
var ( var (
ModuleRegistryService = moduleRegistryService{} ModuleRegistry = moduleRegistryService{}
) )
type moduleRegistryService struct{} type moduleRegistryService struct{}
@@ -104,24 +104,38 @@ func (moduleRegistryService) HandleDeleteModulesCommand(deleteModules cluster.De
return len(deletedModules) 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 { func (moduleRegistryService) GetAggregatedModuleInfo(state state.ReadonlyState) []domain.ModuleInfo {
modules := state.Modules().GetAll() modules := state.Modules().GetAll()
modulesLen := len(modules) modulesLen := len(modules)
result := make([]domain.ModuleInfo, 0, modulesLen) result := make([]domain.ModuleInfo, 0, modulesLen)
resMap := make(map[string]domain.ModuleInfo, modulesLen) resMap := make(map[string]domain.ModuleInfo, modulesLen)
nameIdMap := make(map[string]string)
idList := make([]string, modulesLen) idList := make([]string, modulesLen)
for i, module := range modules { for i, module := range modules {
idList[i] = module.Id idList[i] = module.Id
active := state.Mesh().BackendExist(structure.BackendDeclaration{ModuleName: module.Name})
info := domain.ModuleInfo{ info := domain.ModuleInfo{
Id: module.Id, Id: module.Id,
Name: module.Name, Name: module.Name,
Active: active,
CreatedAt: module.CreatedAt, CreatedAt: module.CreatedAt,
LastConnectedAt: module.LastConnectedAt, LastConnectedAt: module.LastConnectedAt,
LastDisconnectedAt: module.LastDisconnectedAt, LastDisconnectedAt: module.LastDisconnectedAt,
} }
resMap[module.Id] = info resMap[module.Id] = info
nameIdMap[module.Name] = module.Id
} }
configs := state.Configs().GetByModuleIds(idList) configs := state.Configs().GetByModuleIds(idList)
@@ -131,9 +145,9 @@ func (moduleRegistryService) GetAggregatedModuleInfo(state state.ReadonlyState)
Config: configs[i], Config: configs[i],
Valid: false, Valid: false,
}) })
resMap[configs[i].ModuleId] = info resMap[configs[i].ModuleId] = info
} }
schemas := state.Schemas().GetByModuleIds(idList) schemas := state.Schemas().GetByModuleIds(idList)
for _, s := range schemas { for _, s := range schemas {
info := resMap[s.ModuleId] info := resMap[s.ModuleId]
@@ -153,23 +167,41 @@ func (moduleRegistryService) GetAggregatedModuleInfo(state state.ReadonlyState)
backends := state.Mesh().GetBackends(info.Name) backends := state.Mesh().GetBackends(info.Name)
conns := make([]domain.Connection, 0, len(backends)) 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 { for _, back := range backends {
con := domain.Connection{ con := domain.Connection{
Version: back.Version, Version: back.Version,
LibVersion: back.LibVersion, LibVersion: back.LibVersion,
Address: back.Address, 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 { sort.Slice(con.Endpoints, func(i, j int) bool {
return con.Endpoints[i].Path < con.Endpoints[j].Path return con.Endpoints[i].Path < con.Endpoints[j].Path
}) })
con.EstablishedAt = info.LastConnectedAt con.EstablishedAt = info.LastConnectedAt
conns = append(conns, con) 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 { sort.Slice(conns, func(i, j int) bool {
return conns[i].EstablishedAt.Before(conns[j].EstablishedAt) return conns[i].EstablishedAt.Before(conns[j].EstablishedAt)
}) })
info.Status = conns info.Status = conns
info.Active = len(conns) > 0
result = append(result, info) result = append(result, info)
} }
+40
View File
@@ -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
View File
@@ -1,12 +1,9 @@
package service package service
import ( import (
"context"
"encoding/json" "encoding/json"
"github.com/cenkalti/backoff/v4"
etp "github.com/integration-system/isp-etp-go/v2" 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" "github.com/integration-system/isp-lib/v2/utils"
log "github.com/integration-system/isp-log" log "github.com/integration-system/isp-log"
"isp-config-service/codes" "isp-config-service/codes"
@@ -14,62 +11,44 @@ import (
"isp-config-service/store/state" "isp-config-service/store/state"
) )
const ( var Routes routesService
RoutesSubscribersRoom = "__routesSubscribers"
)
var RoutesService routesService
type routesService struct{} type routesService struct{}
func (rs *routesService) HandleDisconnect(connID string) { func (rs *routesService) HandleDisconnect(connID string) {
holder.EtpServer.Rooms().LeaveByConnId(connID, RoutesSubscribersRoom) holder.EtpServer.Rooms().LeaveByConnId(connID, Room.RoutesSubscribers())
} }
func (rs *routesService) SubscribeRoutes(conn etp.Conn, mesh state.ReadonlyMesh) { 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() routes := mesh.GetRoutes()
go func(conn etp.Conn, routes structure.RoutingConfig) { body, err := json.Marshal(routes)
err := rs.sendRoutes(conn, utils.ConfigSendRoutesWhenConnected, routes) if err != nil {
panic(err)
}
go func() {
err := EmitConnWithTimeout(conn, utils.ConfigSendRoutesWhenConnected, body)
if err != nil { 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) { func (rs *routesService) BroadcastRoutes(mesh state.ReadonlyMesh) {
routes := mesh.GetRoutes() routes := mesh.GetRoutes()
go func(routes structure.RoutingConfig) { body, err := json.Marshal(routes)
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)
if err != nil { 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 { go func() {
if bytes, err := json.Marshal(routes); err != nil { conns := holder.EtpServer.Rooms().ToBroadcast(Room.RoutesSubscribers())
return err for _, conn := range conns {
} else { err := EmitConnWithTimeout(conn, utils.ConfigSendRoutesChanged, body)
bf := backoff.WithMaxRetries(backoff.NewConstantBackOff(messagesBackoffInterval), messagesBackoffMaxRetries) if err != nil {
err := backoff.Retry(func() error { log.Errorf(codes.RoutesServiceSendRoutesError, "broadcast routes to %s: %v", conn.RemoteAddr(), err)
return conn.Emit(context.Background(), event, bytes) }
}, bf)
if err != nil {
return err
} }
} }()
return nil
} }
+1 -1
View File
@@ -11,7 +11,7 @@ import (
) )
var ( var (
SchemaService schemaService Schema schemaService
) )
type schemaService struct{} type schemaService struct{}
+75
View File
@@ -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
View File
@@ -1,6 +1,8 @@
package store package store
import ( import (
"time"
"github.com/integration-system/isp-lib/v2/structure" "github.com/integration-system/isp-lib/v2/structure"
"github.com/pkg/errors" "github.com/pkg/errors"
"isp-config-service/cluster" "isp-config-service/cluster"
@@ -15,7 +17,7 @@ func (s *Store) applyUpdateBackendDeclarationCommand(data []byte) (interface{},
if err != nil { if err != nil {
return nil, errors.WithMessage(err, "unmarshal structure.BackendDeclaration") return nil, errors.WithMessage(err, "unmarshal structure.BackendDeclaration")
} }
service.ClusterMeshService.HandleUpdateBackendDeclarationCommand(declaration, s.state) service.ClusterMesh.HandleUpdateBackendDeclarationCommand(declaration, s.state)
return nil, nil return nil, nil
} }
@@ -25,7 +27,7 @@ func (s *Store) applyDeleteBackendDeclarationCommand(data []byte) (interface{},
if err != nil { if err != nil {
return nil, errors.WithMessage(err, "unmarshal structure.BackendDeclaration") return nil, errors.WithMessage(err, "unmarshal structure.BackendDeclaration")
} }
service.ClusterMeshService.HandleDeleteBackendDeclarationCommand(declaration, s.state) service.ClusterMesh.HandleDeleteBackendDeclarationCommand(declaration, s.state)
return nil, nil return nil, nil
} }
@@ -35,7 +37,7 @@ func (s *Store) applyUpdateConfigSchemaCommand(data []byte) (interface{}, error)
if err != nil { if err != nil {
return nil, errors.WithMessage(err, "unmarshal entity.ConfigSchema") 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 { if err != nil {
return nil, errors.WithMessage(err, "update config schema") return nil, errors.WithMessage(err, "update config schema")
} }
@@ -48,7 +50,7 @@ func (s *Store) applyModuleConnectedCommand(data []byte) (interface{}, error) {
if err != nil { if err != nil {
return nil, errors.WithMessage(err, "unmarshal entity.Module") return nil, errors.WithMessage(err, "unmarshal entity.Module")
} }
service.ModuleRegistryService.HandleModuleConnectedCommand(module, s.state) service.ModuleRegistry.HandleModuleConnectedCommand(module, s.state)
return nil, nil return nil, nil
} }
@@ -58,7 +60,7 @@ func (s *Store) applyModuleDisconnectedCommand(data []byte) (interface{}, error)
if err != nil { if err != nil {
return nil, errors.WithMessage(err, "unmarshal entity.Module") return nil, errors.WithMessage(err, "unmarshal entity.Module")
} }
service.ModuleRegistryService.HandleModuleDisconnectedCommand(module, s.state) service.ModuleRegistry.HandleModuleDisconnectedCommand(module, s.state)
return nil, nil return nil, nil
} }
@@ -68,7 +70,7 @@ func (s *Store) applyDeleteModulesCommand(data []byte) (interface{}, error) {
if err != nil { if err != nil {
return nil, errors.WithMessage(err, "unmarshal cluster.DeleteModules") 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 return domain.DeleteResponse{Deleted: deleted}, nil
} }
@@ -108,7 +110,7 @@ func (s *Store) applyDeleteCommonConfigsCommand(data []byte) (interface{}, error
if err != nil { if err != nil {
return nil, errors.WithMessage(err, "unmarshal cluster.DeleteCommonConfig") 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 return response, nil
} }
@@ -118,6 +120,28 @@ func (s *Store) applyUpsertCommonConfigCommand(data []byte) (interface{}, error)
if err != nil { if err != nil {
return nil, errors.WithMessage(err, "unmarshal cluster.UpsertCommonConfig") 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 return response, nil
} }
+6 -1
View File
@@ -24,6 +24,11 @@ func NewStateFromRepository() (*state.State, error) {
return nil, errors.WithMessage(err, "load common configs") 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 return st, nil
} }
+21 -45
View File
@@ -11,8 +11,6 @@ type WriteableMesh interface {
} }
type ReadonlyMesh interface { type ReadonlyMesh interface {
CheckBackendChanged(backend structure.BackendDeclaration) (changed bool)
BackendExist(backend structure.BackendDeclaration) (exist bool)
GetModuleAddresses(moduleName string) []structure.AddressConfiguration GetModuleAddresses(moduleName string) []structure.AddressConfiguration
GetBackends(module string) []structure.BackendDeclaration GetBackends(module string) []structure.BackendDeclaration
GetRoutes() structure.RoutingConfig GetRoutes() structure.RoutingConfig
@@ -25,14 +23,8 @@ type Mesh struct {
ModulesMap map[string]NodesMap ModulesMap map[string]NodesMap
} }
func (m Mesh) BackendExist(backend structure.BackendDeclaration) (exist bool) { func NewMesh() *Mesh {
address := backend.Address.GetAddress() return &Mesh{ModulesMap: make(map[string]NodesMap)}
if nodes, ok := m.ModulesMap[backend.ModuleName]; ok {
if _, ok := nodes[address]; ok {
exist = true
}
}
return
} }
func (m Mesh) GetBackends(module string) []structure.BackendDeclaration { 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 { func (m Mesh) GetRoutes() structure.RoutingConfig {
routes := structure.RoutingConfig{} routes := structure.RoutingConfig{}
for _, node := range m.ModulesMap { for _, nodes := range m.ModulesMap {
for _, backend := range node { for _, backend := range nodes {
routes = append(routes, backend) routes = append(routes, backend)
} }
} }
return routes return routes
} }
func (m Mesh) CheckBackendChanged(backend structure.BackendDeclaration) (changed bool) { func (m *Mesh) UpsertBackend(backend structure.BackendDeclaration) bool {
address := backend.Address.GetAddress() 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) { nodes, ok := m.ModulesMap[backend.ModuleName]
address := backend.Address.GetAddress() if !ok {
if nodes, ok := m.ModulesMap[backend.ModuleName]; ok {
if oldBackend, ok := nodes[address]; ok {
if oldBackend.Version != backend.Version || !oldBackend.IsPathsEqual(backend.Endpoints) || oldBackend.LibVersion != backend.LibVersion {
nodes[address] = backend
changed = true
}
} else {
nodes[address] = backend
changed = true
}
} else {
m.ModulesMap[backend.ModuleName] = NodesMap{address: backend} 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) { func (m *Mesh) DeleteBackend(backend structure.BackendDeclaration) (deleted bool) {
@@ -113,7 +93,3 @@ func (m *Mesh) DeleteBackend(backend structure.BackendDeclaration) (deleted bool
} }
return return
} }
func NewMesh() *Mesh {
return &Mesh{ModulesMap: make(map[string]NodesMap)}
}
+14 -1
View File
@@ -10,6 +10,7 @@ type State struct {
SchemasStore *SchemaStore SchemasStore *SchemaStore
ModulesStore *ModuleStore ModulesStore *ModuleStore
CommonConfigsStore *CommonConfigStore CommonConfigsStore *CommonConfigStore
VersionConfigStore *VersionConfigStore
} }
func (s State) Mesh() ReadonlyMesh { func (s State) Mesh() ReadonlyMesh {
@@ -32,6 +33,10 @@ func (s State) CommonConfigs() ReadonlyCommonConfigStore {
return s.CommonConfigsStore return s.CommonConfigsStore
} }
func (s State) VersionConfig() ReadonlyVersionConfigStore {
return s.VersionConfigStore
}
func (s *State) WritableMesh() WriteableMesh { func (s *State) WritableMesh() WriteableMesh {
return s.MeshStore return s.MeshStore
} }
@@ -52,6 +57,10 @@ func (s *State) WritableCommonConfigs() WriteableCommonConfigStore {
return s.CommonConfigsStore return s.CommonConfigsStore
} }
func (s *State) WriteableVersionConfigStore() WriteableVersionConfigStore {
return s.VersionConfigStore
}
type WritableState interface { type WritableState interface {
ReadonlyState ReadonlyState
WritableMesh() WriteableMesh WritableMesh() WriteableMesh
@@ -59,6 +68,7 @@ type WritableState interface {
WritableSchemas() WriteableSchemaStore WritableSchemas() WriteableSchemaStore
WritableModules() WriteableModuleStore WritableModules() WriteableModuleStore
WritableCommonConfigs() WriteableCommonConfigStore WritableCommonConfigs() WriteableCommonConfigStore
WriteableVersionConfigStore() WriteableVersionConfigStore
} }
type ReadonlyState interface { type ReadonlyState interface {
@@ -67,6 +77,7 @@ type ReadonlyState interface {
Schemas() ReadonlySchemaStore Schemas() ReadonlySchemaStore
Modules() ReadonlyModuleStore Modules() ReadonlyModuleStore
CommonConfigs() ReadonlyCommonConfigStore CommonConfigs() ReadonlyCommonConfigStore
VersionConfig() ReadonlyVersionConfigStore
} }
func NewState() *State { func NewState() *State {
@@ -76,16 +87,18 @@ func NewState() *State {
SchemasStore: NewSchemaStore(), SchemasStore: NewSchemaStore(),
ModulesStore: NewModuleStore(), ModulesStore: NewModuleStore(),
CommonConfigsStore: NewCommonConfigStore(), CommonConfigsStore: NewCommonConfigStore(),
VersionConfigStore: NewVersionConfigStore(),
} }
} }
func NewStateFromSnapshot(configs []entity.Config, schemas []entity.ConfigSchema, 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{ return &State{
MeshStore: NewMesh(), MeshStore: NewMesh(),
ConfigsStore: &ConfigStore{Configs: configs}, ConfigsStore: &ConfigStore{Configs: configs},
SchemasStore: &SchemaStore{Schemas: schemas}, SchemasStore: &SchemaStore{Schemas: schemas},
ModulesStore: &ModuleStore{Modules: modules}, ModulesStore: &ModuleStore{Modules: modules},
CommonConfigsStore: &CommonConfigStore{Configs: commConfigs}, CommonConfigsStore: &CommonConfigStore{Configs: commConfigs},
VersionConfigStore: NewVersionConfigStoreFromSnapshot(versionStore),
} }
} }
+89
View File
@@ -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
View File
@@ -1,7 +1,6 @@
package store package store
import ( import (
"encoding/binary"
"fmt" "fmt"
"io" "io"
"sync" "sync"
@@ -23,7 +22,7 @@ var (
type Store struct { type Store struct {
state *state.State state *state.State
lock sync.RWMutex 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{} { 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 { if len(l.Data) < cluster.CommandSizeBytes {
log.Errorf(codes.ApplyLogCommandError, "invalid log data command: %s", l.Data) log.Errorf(codes.ApplyLogCommandError, "invalid log data command: %s", l.Data)
} }
command := binary.BigEndian.Uint64(l.Data[:8]) command := cluster.ParseCommand(l.Data)
log.Debugf(0, "Apply %d command. Data: %s", command, l.Data) log.Debugf(0, "Apply %s. Data: %s", command, l.Data)
var ( var (
result interface{} result interface{}
@@ -119,7 +118,7 @@ func NewStateStore(st *state.State) *Store {
store := &Store{ store := &Store{
state: st, state: st,
} }
store.handlers = map[uint64]func([]byte) (interface{}, error){ store.handlers = map[cluster.Command]func([]byte) (interface{}, error){
cluster.UpdateBackendDeclarationCommand: store.applyUpdateBackendDeclarationCommand, cluster.UpdateBackendDeclarationCommand: store.applyUpdateBackendDeclarationCommand,
cluster.DeleteBackendDeclarationCommand: store.applyDeleteBackendDeclarationCommand, cluster.DeleteBackendDeclarationCommand: store.applyDeleteBackendDeclarationCommand,
cluster.ModuleConnectedCommand: store.applyModuleConnectedCommand, cluster.ModuleConnectedCommand: store.applyModuleConnectedCommand,
@@ -131,6 +130,8 @@ func NewStateStore(st *state.State) *Store {
cluster.UpsertConfigCommand: store.applyUpsertConfigCommand, cluster.UpsertConfigCommand: store.applyUpsertConfigCommand,
cluster.DeleteCommonConfigsCommand: store.applyDeleteCommonConfigsCommand, cluster.DeleteCommonConfigsCommand: store.applyDeleteCommonConfigsCommand,
cluster.UpsertCommonConfigCommand: store.applyUpsertCommonConfigCommand, cluster.UpsertCommonConfigCommand: store.applyUpsertCommonConfigCommand,
cluster.BroadcastEventCommand: store.applyBroadcastEventCommand,
cluster.DeleteVersionConfigCommand: store.applyDeleteVersionConfigCommand,
} }
return store return store
} }
-51
View File
@@ -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
View File
@@ -2,6 +2,7 @@ package subs
import ( import (
"fmt" "fmt"
"time"
"github.com/asaskevich/govalidator" "github.com/asaskevich/govalidator"
etp "github.com/integration-system/isp-etp-go/v2" 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) SetBackendDeclaration(conn, declaration)
command := cluster.PrepareUpdateBackendDeclarationCommand(declaration) command := cluster.PrepareUpdateBackendDeclarationCommand(declaration)
_, err = SyncApplyCommand(command, "UpdateBackendDeclarationCommand") _, err = SyncApplyCommand(command)
if err != nil { if err != nil {
return []byte(err.Error()) return []byte(err.Error())
} }
@@ -52,9 +53,9 @@ func (h *SocketEventHandler) handleModuleRequirements(conn etp.Conn, data []byte
} }
h.store.VisitReadonlyState(func(state state.ReadonlyState) { 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 { if declaration.RequireRoutes {
service.RoutesService.SubscribeRoutes(conn, state.Mesh()) service.Routes.SubscribeRoutes(conn, state.Mesh())
} }
}) })
return []byte(utils.WsOkResponse) return []byte(utils.WsOkResponse)
@@ -90,13 +91,13 @@ func (h *SocketEventHandler) handleConfigSchema(conn etp.Conn, data []byte) []by
UpdatedAt: now, UpdatedAt: now,
} }
command := cluster.PrepareUpdateConfigSchemaCommand(schema) command := cluster.PrepareUpdateConfigSchemaCommand(schema)
_, _ = SyncApplyCommand(command, "UpdateConfigSchemaCommand") _, _ = SyncApplyCommand(command)
var configs []entity.Config var configs []entity.Config
h.store.VisitReadonlyState(func(readState state.ReadonlyState) { h.store.VisitReadonlyState(func(readState state.ReadonlyState) {
configs = readState.Configs().GetByModuleIds([]string{module.Id}) configs = readState.Configs().GetByModuleIds([]string{module.Id})
}) })
if len(configs) == 0 { //create empty default config if len(configs) == 0 { // create empty default config
if configSchema.DefaultConfig == nil { if configSchema.DefaultConfig == nil {
configSchema.DefaultConfig = make(map[string]interface{}) configSchema.DefaultConfig = make(map[string]interface{})
} }
@@ -109,13 +110,15 @@ func (h *SocketEventHandler) handleConfigSchema(conn etp.Conn, data []byte) []by
UpdatedAt: now, UpdatedAt: now,
} }
upsertConfig := cluster.UpsertConfig{ upsertConfig := cluster.UpsertConfig{
Config: config, Config: config,
Create: true, Create: true,
Unsafe: true, Unsafe: true,
VersionId: state.GenerateId(),
VersionCreateAt: time.Now(),
} }
command := cluster.PrepareUpsertConfigCommand(upsertConfig) command := cluster.PrepareUpsertConfigCommand(upsertConfig)
_, _ = SyncApplyCommand(command, "UpsertConfigCommand") _, _ = SyncApplyCommand(command)
} }
return []byte(utils.WsOkResponse) return []byte(utils.WsOkResponse)
} }
+4 -2
View File
@@ -1,6 +1,8 @@
package subs package subs
import ( import (
"fmt"
etp "github.com/integration-system/isp-etp-go/v2" etp "github.com/integration-system/isp-etp-go/v2"
log "github.com/integration-system/isp-log" log "github.com/integration-system/isp-log"
"isp-config-service/cluster" "isp-config-service/cluster"
@@ -14,8 +16,8 @@ func (h *SocketEventHandler) applyCommandOnLeader(_ etp.Conn, cmd []byte) (data
obj, err := holder.ClusterClient.SyncApplyOnLeader(cmdCopy) obj, err := holder.ClusterClient.SyncApplyOnLeader(cmdCopy)
if err != nil { if err != nil {
var logResponse cluster.ApplyLogResponse var logResponse cluster.ApplyLogResponse
logResponse.ApplyError = err.Error() logResponse.ApplyError = fmt.Sprintf("SyncApplyOnLeader: %v", err)
data, err = json.Marshal(obj) data, err = json.Marshal(logResponse)
if err != nil { if err != nil {
log.Fatalf(codes.SyncApplyError, "marshaling ApplyLogResponse: %v", err) log.Fatalf(codes.SyncApplyError, "marshaling ApplyLogResponse: %v", err)
} }
+1 -2
View File
@@ -12,12 +12,11 @@ type connectionState struct {
} }
func IsConfigClusterNode(conn etp.Conn) bool { func IsConfigClusterNode(conn etp.Conn) bool {
isCluster := conn.URL().Query().Get(cluster.ClusterParam) isCluster := conn.URL().Query().Get(cluster.GETParam)
return isCluster == "true" return isCluster == "true"
} }
func Parameters(conn etp.Conn) (moduleName string, err error) { func Parameters(conn etp.Conn) (moduleName string, err error) {
// TODO remove instanceUUID from isp-lib
_, moduleName, err = utils.ParseParameters(conn.URL().RawQuery) _, moduleName, err = utils.ParseParameters(conn.URL().RawQuery)
return moduleName, err return moduleName, err
} }
+7 -4
View File
@@ -1,17 +1,18 @@
package subs package subs
import ( import (
"context"
"errors" "errors"
etp "github.com/integration-system/isp-etp-go/v2" etp "github.com/integration-system/isp-etp-go/v2"
log "github.com/integration-system/isp-log" log "github.com/integration-system/isp-log"
"isp-config-service/cluster"
"isp-config-service/codes" "isp-config-service/codes"
"isp-config-service/holder" "isp-config-service/holder"
"isp-config-service/service"
) )
func EmitConn(conn etp.Conn, event string, body []byte) { 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 { if err != nil {
log.WithMetadata(map[string]interface{}{ log.WithMetadata(map[string]interface{}{
"event": event, "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) applyLogResponse, err := holder.ClusterClient.SyncApply(command)
if err != nil { if err != nil {
commandName := cluster.ParseCommand(command).String()
log.WithMetadata(map[string]interface{}{ log.WithMetadata(map[string]interface{}{
"command": string(command), "command": string(command),
"commandName": commandName, "commandName": commandName,
@@ -29,6 +31,7 @@ func SyncApplyCommand(command []byte, commandName string) (interface{}, error) {
return nil, err return nil, err
} }
if applyLogResponse != nil && applyLogResponse.ApplyError != "" { if applyLogResponse != nil && applyLogResponse.ApplyError != "" {
commandName := cluster.ParseCommand(command).String()
log.WithMetadata(map[string]interface{}{ log.WithMetadata(map[string]interface{}{
"result": string(applyLogResponse.Result), "result": string(applyLogResponse.Result),
"applyError": applyLogResponse.ApplyError, "applyError": applyLogResponse.ApplyError,
@@ -41,7 +44,7 @@ func SyncApplyCommand(command []byte, commandName string) (interface{}, error) {
func FormatErrorConnection(err error) []byte { func FormatErrorConnection(err error) []byte {
errMap := map[string]interface{}{ errMap := map[string]interface{}{
"error": err, "error": err.Error(),
} }
data, _ := json.Marshal(errMap) data, _ := json.Marshal(errMap)
return data return data
+12 -11
View File
@@ -43,7 +43,7 @@ func (h *SocketEventHandler) handleConnect(conn etp.Conn) {
_ = conn.Close() _ = conn.Close()
return return
} }
holder.EtpServer.Rooms().Join(conn, moduleName+service.ConfigWatchersRoomSuffix) holder.EtpServer.Rooms().Join(conn, service.Room.Module(moduleName))
now := state.GenerateDate() now := state.GenerateDate()
module := entity.Module{ module := entity.Module{
Id: state.GenerateId(), Id: state.GenerateId(),
@@ -52,7 +52,7 @@ func (h *SocketEventHandler) handleConnect(conn etp.Conn) {
LastConnectedAt: now, LastConnectedAt: now,
} }
command := cluster.PrepareModuleConnectedCommand(module) command := cluster.PrepareModuleConnectedCommand(module)
_, err = SyncApplyCommand(command, "ModuleConnectedCommand") _, err = SyncApplyCommand(command)
if err != nil && !isClusterNode { if err != nil && !isClusterNode {
EmitConn(conn, utils.ErrorConnection, FormatErrorConnection(err)) EmitConn(conn, utils.ErrorConnection, FormatErrorConnection(err))
_ = conn.Close() _ = conn.Close()
@@ -79,11 +79,11 @@ func (h *SocketEventHandler) handleConnect(conn etp.Conn) {
EmitConn(conn, utils.ConfigSendConfigWhenConnected, data) EmitConn(conn, utils.ConfigSendConfigWhenConnected, data)
} }
func (h *SocketEventHandler) handleDisconnect(conn etp.Conn, disconnectErr error) { func (h *SocketEventHandler) handleDisconnect(conn etp.Conn, _ error) {
moduleName, _ := Parameters(conn) 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 != "" { if moduleName != "" {
holder.EtpServer.Rooms().Leave(conn, moduleName+service.ConfigWatchersRoomSuffix) holder.EtpServer.Rooms().Leave(conn, service.Room.Module(moduleName))
now := state.GenerateDate() now := state.GenerateDate()
module := entity.Module{ module := entity.Module{
Id: state.GenerateId(), Id: state.GenerateId(),
@@ -93,20 +93,21 @@ func (h *SocketEventHandler) handleDisconnect(conn etp.Conn, disconnectErr error
LastDisconnectedAt: now, LastDisconnectedAt: now,
} }
command := cluster.PrepareModuleDisconnectedCommand(module) command := cluster.PrepareModuleDisconnectedCommand(module)
_, _ = SyncApplyCommand(command, "ModuleDisconnectedCommand") _, _ = SyncApplyCommand(command)
} }
service.DiscoveryService.HandleDisconnect(conn.ID()) service.Discovery.HandleDisconnect(conn.ID())
service.RoutesService.HandleDisconnect(conn.ID()) service.Routes.HandleDisconnect(conn.ID())
backend, ok := ExtractBackendDeclaration(conn) backend, ok := ExtractBackendDeclaration(conn)
if ok { if ok {
command := cluster.PrepareDeleteBackendDeclarationCommand(backend) command := cluster.PrepareDeleteBackendDeclarationCommand(backend)
_, _ = SyncApplyCommand(command, "DeleteBackendDeclarationCommand") _, _ = SyncApplyCommand(command)
} }
} }
func (h *SocketEventHandler) handleError(_ etp.Conn, err error) { func (h *SocketEventHandler) handleError(conn etp.Conn, err error) {
log.Warnf(codes.WebsocketError, "isp-etp: %v", err) 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 { func NewSocketEventHandler(server etp.Server, store *store.Store) *SocketEventHandler {