From 28aa3eae33a1b08cbbdef8da20a9092f3686ab4f Mon Sep 17 00:00:00 2001 From: Maxim Merzhanov Date: Mon, 23 Mar 2020 16:49:21 +0300 Subject: [PATCH] add module/broadcast_event method --- CHANGELOG.md | 3 +++ cluster/const.go | 10 ++++++++-- cluster/const_string.go | 5 +++-- cluster/events.go | 8 +++++++- cluster/leader_client.go | 2 +- controller/helpers.go | 8 +++++--- controller/module.go | 19 +++++++++++++++++++ docs/swagger.yaml | 31 +++++++++++++++++++++++++++++++ helper/handler.go | 4 ++++ service/discovery.go | 11 +++++++++++ store/apply.go | 10 ++++++++++ store/store.go | 3 ++- subs/conn.go | 2 +- 13 files changed, 105 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f0b258..6b441d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/cluster/const.go b/cluster/const.go index 233c9d4..b52fa51 100644 --- a/cluster/const.go +++ b/cluster/const.go @@ -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)) diff --git a/cluster/const_string.go b/cluster/const_string.go index 5aa85ab..5fdb36c 100644 --- a/cluster/const_string.go +++ b/cluster/const_string.go @@ -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 diff --git a/cluster/events.go b/cluster/events.go index 1d20546..48c4e63 100644 --- a/cluster/events.go +++ b/cluster/events.go @@ -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 diff --git a/cluster/leader_client.go b/cluster/leader_client.go index 101ddad..a81db4d 100644 --- a/cluster/leader_client.go +++ b/cluster/leader_client.go @@ -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") diff --git a/controller/helpers.go b/controller/helpers.go index 9cc6d99..0895ccc 100644 --- a/controller/helpers.go +++ b/controller/helpers.go @@ -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 } diff --git a/controller/module.go b/controller/module.go index 373e9eb..344f772 100644 --- a/controller/module.go +++ b/controller/module.go @@ -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, diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 3bde584..aa444f2 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -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: diff --git a/helper/handler.go b/helper/handler.go index 45fb277..e03fd6c 100644 --- a/helper/handler.go +++ b/helper/handler.go @@ -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, diff --git a/service/discovery.go b/service/discovery.go index 7b2dcfd..a32b971 100644 --- a/service/discovery.go +++ b/service/discovery.go @@ -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 { diff --git a/store/apply.go b/store/apply.go index fa6fd92..a98af9c 100644 --- a/store/apply.go +++ b/store/apply.go @@ -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 +} diff --git a/store/store.go b/store/store.go index f26a479..42f3131 100644 --- a/store/store.go +++ b/store/store.go @@ -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 } diff --git a/subs/conn.go b/subs/conn.go index fdfe6cb..b447366 100644 --- a/subs/conn.go +++ b/subs/conn.go @@ -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" }