add module/broadcast_event method

This commit is contained in:
Maxim Merzhanov committed 2020-03-23 16:49:21 +03:00
1 parent 96dee8dee3
commit 28aa3eae33
13 files changed
+105 -11

No files matched your search

+3
View File
@@ -1,3 +1,6 @@
### upcoming
* add method `/module/broadcast_event` to broadcast arbitrary event to all connected modules
### v2.2.1
* update deps
* fix bug in json schema marshaling/unmarshaling
+8 -2
View File
@@ -15,12 +15,12 @@ const (
ApplyCommandEvent = "CONFIG_CLUSTER:APPLY_COMMAND"
CommandSizeBytes = 8
ClusterParam = "cluster"
GETParam = "cluster"
)
type Command uint64
// need: go get golang.org/x/tools/cmd/stringer
// needed: go get golang.org/x/tools/cmd/stringer
//go:generate stringer -type=Command -output const_string.go
const (
_ Command = iota
@@ -39,6 +39,8 @@ const (
DeleteCommonConfigsCommand
UpsertCommonConfigCommand
BroadcastEventCommand
)
func PrepareUpdateBackendDeclarationCommand(backend structure.BackendDeclaration) []byte {
@@ -85,6 +87,10 @@ func PrepareUpsertCommonConfigCommand(config UpsertCommonConfig) []byte {
return prepareCommand(UpsertCommonConfigCommand, config)
}
func PrepareBroadcastEventCommand(event BroadcastEvent) []byte {
return prepareCommand(BroadcastEventCommand, event)
}
func prepareCommand(command Command, payload interface{}) []byte {
cmd := make([]byte, 8)
binary.BigEndian.PutUint64(cmd, uint64(command))
+3 -2
View File
@@ -19,11 +19,12 @@ func _() {
_ = x[UpsertConfigCommand-9]
_ = x[DeleteCommonConfigsCommand-10]
_ = x[UpsertCommonConfigCommand-11]
_ = x[BroadcastEventCommand-12]
}
const _Command_name = "UpdateBackendDeclarationCommandDeleteBackendDeclarationCommandUpdateConfigSchemaCommandModuleConnectedCommandModuleDisconnectedCommandDeleteModulesCommandActivateConfigCommandDeleteConfigsCommandUpsertConfigCommandDeleteCommonConfigsCommandUpsertCommonConfigCommand"
const _Command_name = "UpdateBackendDeclarationCommandDeleteBackendDeclarationCommandUpdateConfigSchemaCommandModuleConnectedCommandModuleDisconnectedCommandDeleteModulesCommandActivateConfigCommandDeleteConfigsCommandUpsertConfigCommandDeleteCommonConfigsCommandUpsertCommonConfigCommandBroadcastEventCommand"
var _Command_index = [...]uint16{0, 31, 62, 87, 109, 134, 154, 175, 195, 214, 240, 265}
var _Command_index = [...]uint16{0, 31, 62, 87, 109, 134, 154, 175, 195, 214, 240, 265, 286}
func (i Command) String() string {
i -= 1
+7 -1
View File
@@ -3,9 +3,10 @@ package cluster
import (
json2 "encoding/json"
"fmt"
"time"
"google.golang.org/grpc/codes"
"isp-config-service/entity"
"time"
)
type ApplyLogResponse struct {
@@ -45,6 +46,11 @@ type UpsertCommonConfig struct {
Create bool
}
type BroadcastEvent struct {
Event string
Payload json2.RawMessage
}
type ResponseWithError struct {
Response interface{}
Error string
+1 -1
View File
@@ -107,7 +107,7 @@ func getURL(address string) string {
cfg := config.Get().(*conf.Configuration)
params := url.Values{}
params.Add(ClusterParam, "true")
params.Add(GETParam, "true")
// TODO выпилить instance_uuid ?
params.Add(utils.ModuleNameGetParamKey, cfg.ModuleName)
params.Add(utils.InstanceUuidGetParamKey, "9d89354b-c728-4b48-b002-a7d3b229f151")
+5 -3
View File
@@ -31,9 +31,11 @@ func PerformSyncApply(command []byte, commandName string, responsePtr interface{
}).Warnf(codes2.SyncApplyError, "apply command")
return unknownError()
}
err = json.Unmarshal(applyLogResponse.Result, responsePtr)
if err != nil {
return unknownError()
if responsePtr != nil {
err = json.Unmarshal(applyLogResponse.Result, responsePtr)
if err != nil {
return unknownError()
}
}
return nil
}
+19
View File
@@ -85,6 +85,25 @@ func (c *module) GetModuleByName(req domain.GetByModuleNameRequest) (*entity.Mod
return module, nil
}
// @Summary Метод отправки события всем подключенным модулям
// @Description Модуль
// @Tags Модули
// @Accept json
// @Produce json
// @Param body body cluster.BroadcastEvent true "событие"
// @Success 200 ""
// @Failure 500 {object} structure.GrpcError
// @Router /module/broadcast_event [POST]
func (c *module) BroadcastEvent(req cluster.BroadcastEvent) error {
command := cluster.PrepareBroadcastEventCommand(req)
err := PerformSyncApply(command, "BroadcastEventCommand", nil)
if err != nil {
return err
}
return nil
}
func NewModule(rstore *store.Store) *module {
return &module{
rstore: rstore,
+31
View File
@@ -1,5 +1,13 @@
basePath: /api/config
definitions:
cluster.BroadcastEvent:
properties:
event:
type: string
payload:
$ref: '#/definitions/json.RawMessage'
type: object
type: object
domain.CommonConfigLinks:
additionalProperties:
items:
@@ -807,6 +815,29 @@ paths:
summary: Метод активации конфигурации для модуля
tags:
- Конфигурация
/module/broadcast_event:
post:
consumes:
- application/json
description: Модуль
parameters:
- description: событие
in: body
name: body
required: true
schema:
$ref: '#/definitions/cluster.BroadcastEvent'
produces:
- application/json
responses:
"200": {}
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/structure.GrpcError'
summary: Метод отправки события всем подключенным модулям
tags:
- Модули
/module/delete_module:
post:
consumes:
+4
View File
@@ -3,6 +3,7 @@ package helper
import (
"github.com/integration-system/isp-lib/v2/structure"
"isp-config-service/cluster"
"isp-config-service/controller"
"isp-config-service/domain"
"isp-config-service/entity"
@@ -13,6 +14,8 @@ type Handlers struct {
DeleteModules func(identities []string) (*domain.DeleteResponse, error) `method:"delete_module" group:"module" inner:"true"`
GetModulesInfo func() ([]domain.ModuleInfo, error) `method:"get_modules_info" group:"module" inner:"true"`
GetModuleByName func(req domain.GetByModuleNameRequest) (*entity.Module, error) `method:"get_by_name" group:"module" inner:"true"`
BroadcastEvent func(req cluster.BroadcastEvent) error `method:"broadcast_event" group:"module" inner:"true"`
// ===== CONFIG =====
GetActiveConfigByModuleName func(request domain.GetByModuleNameRequest) (*entity.Config, error) `method:"get_active_config_by_module_name" group:"config" inner:"true"`
CreateUpdateConfig func(config domain.CreateUpdateConfigRequest) (*domain.ConfigModuleInfo, error) `method:"create_update_config" group:"config" inner:"true"`
@@ -38,6 +41,7 @@ func GetHandlers() *Handlers {
DeleteModules: controller.Module.DeleteModules,
GetModulesInfo: controller.Module.GetModulesAggregatedInfo,
GetModuleByName: controller.Module.GetModuleByName,
BroadcastEvent: controller.Module.BroadcastEvent,
GetActiveConfigByModuleName: controller.Config.GetActiveConfigByModuleName,
CreateUpdateConfig: controller.Config.CreateUpdateConfig,
+11
View File
@@ -11,6 +11,7 @@ import (
"github.com/integration-system/isp-lib/v2/structure"
"github.com/integration-system/isp-lib/v2/utils"
log "github.com/integration-system/isp-log"
"isp-config-service/cluster"
"isp-config-service/codes"
"isp-config-service/holder"
"isp-config-service/store/state"
@@ -81,6 +82,16 @@ func (ds *discoveryService) BroadcastModuleAddresses(moduleName string, mesh sta
}(event, event, addressList)
}
func (ds *discoveryService) BroadcastEvent(event cluster.BroadcastEvent) {
eventName := event.Event
payload := make([]byte, len(event.Payload))
copy(payload, event.Payload)
go func() {
_ = holder.EtpServer.BroadcastToAll(eventName, payload)
}()
}
func (ds *discoveryService) broadcastAddrList(room string, event string, addressList []structure.AddressConfiguration) error {
bytes, err := json.Marshal(addressList)
if err != nil {
+10
View File
@@ -121,3 +121,13 @@ func (s *Store) applyUpsertCommonConfigCommand(data []byte) (interface{}, error)
response := service.CommonConfigService.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")
}
service.DiscoveryService.BroadcastEvent(event)
return nil, nil
}
+2 -1
View File
@@ -33,7 +33,7 @@ func (s *Store) Apply(l *raft.Log) interface{} {
if len(l.Data) < cluster.CommandSizeBytes {
log.Errorf(codes.ApplyLogCommandError, "invalid log data command: %s", l.Data)
}
command := cluster.Command(binary.BigEndian.Uint64(l.Data[:8]))
command := cluster.Command(binary.BigEndian.Uint64(l.Data[:cluster.CommandSizeBytes]))
log.Debugf(0, "Apply %s. Data: %s", command, l.Data)
var (
@@ -131,6 +131,7 @@ func NewStateStore(st *state.State) *Store {
cluster.UpsertConfigCommand: store.applyUpsertConfigCommand,
cluster.DeleteCommonConfigsCommand: store.applyDeleteCommonConfigsCommand,
cluster.UpsertCommonConfigCommand: store.applyUpsertCommonConfigCommand,
cluster.BroadcastEventCommand: store.applyBroadcastEventCommand,
}
return store
}
+1 -1
View File
@@ -12,7 +12,7 @@ type connectionState struct {
}
func IsConfigClusterNode(conn etp.Conn) bool {
isCluster := conn.URL().Query().Get(cluster.ClusterParam)
isCluster := conn.URL().Query().Get(cluster.GETParam)
return isCluster == "true"
}