migrate to etp
fix raft logger
This commit is contained in:
1 parent
330c160122
commit
652c2d95b8
20 files changed
+359
-439
No files matched your search
Generated
+141
-23
@@ -1,6 +1,41 @@
|
||||
# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
|
||||
|
||||
|
||||
[[projects]]
|
||||
digest = "1:38beba9afeb613a2a1504b118165c1a6caea134160c969980427952c7a475f44"
|
||||
name = "github.com/KyleBanks/depth"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "fec4dc38699e903ea7b44b2887549d2e7cd0a9f1"
|
||||
version = "v1.2.1"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:a2682518d905d662d984ef9959984ef87cecb777d379bfa9d9fe40e78069b3e4"
|
||||
name = "github.com/PuerkitoBio/purell"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "44968752391892e1b0d0b821ee79e9a85fa13049"
|
||||
version = "v1.1.1"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:c739832d67eb1e9cc478a19cc1a1ccd78df0397bf8a32978b759152e205f644b"
|
||||
name = "github.com/PuerkitoBio/urlesc"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "de5bf2ad457846296e2031421a34e2568e304e35"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:125f098c5294814b5d9ce2194f03a435c35a6208f029e61681bed9a893d68133"
|
||||
name = "github.com/alecthomas/template"
|
||||
packages = [
|
||||
".",
|
||||
"parse",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "fb15b899a75114aa79cc930e33c46b577cc664b1"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:7a9140c806333a78122763d08ec6c0d7358c7fff1df8cfbb01881c5dc46e24e5"
|
||||
@@ -49,6 +84,38 @@
|
||||
revision = "c2828203cd70a50dcccfb2761f8b1f8ceef9a8e9"
|
||||
version = "v1.4.7"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:ed15647db08b6d63666bf9755d337725960c302bbfa5e23754b4b915a4797e42"
|
||||
name = "github.com/go-openapi/jsonpointer"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "ed123515f087412cd7ef02e49b0b0a5e6a79a360"
|
||||
version = "v0.19.3"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:451fe53c19443c6941be5d4295edc973a3eb16baccb940efee94284024be03b0"
|
||||
name = "github.com/go-openapi/jsonreference"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "82f31475a8f7a12bc26962f6e26ceade8ea6f66a"
|
||||
version = "v0.19.3"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:55d1c09fc8b3320b6842565249a9e4d0f363bead6f9b8be05c3b47f2c4264eda"
|
||||
name = "github.com/go-openapi/spec"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "8557d72e4f077c2dbe1e48df09e596b6fb9b7991"
|
||||
version = "v0.19.4"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:43d0f99f53acce97119181dcd592321084690c2d462c57680ccb4472ae084949"
|
||||
name = "github.com/go-openapi/swag"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "c3d0f7896d589f3babb99eea24bbc7de98108e72"
|
||||
version = "v0.19.5"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:f9448bfab8ebe44e3d91e4e4475cf92d60789a614652f361df4e41972c9d5caf"
|
||||
name = "github.com/go-pg/pg"
|
||||
@@ -82,27 +149,6 @@
|
||||
revision = "6c65a5562fc06764971b7c5d05c76c75e84bdbf7"
|
||||
version = "v1.3.2"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:324591cd9122f94cc39a87bd44ec71153672c239e2cff5743bfad96b60be3749"
|
||||
name = "github.com/googollee/go-engine.io"
|
||||
packages = [
|
||||
".",
|
||||
"message",
|
||||
"parser",
|
||||
"polling",
|
||||
"transport",
|
||||
"websocket",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "e2f255711dcb2ea41e42c6d9d98c172d7edf6509"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:3eb026ba34d6dd12b45bb6abd63b4e917ebca8d8f3022a139c0881d900ad1bee"
|
||||
name = "github.com/googollee/go-socket.io"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "c8aeb1ed9b49d7de8fef8662efb18f1d289c5f2e"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:e62657cca9badaa308d86e7716083e4c5933bb78e30a17743fc67f50be26f6f4"
|
||||
name = "github.com/gorilla/websocket"
|
||||
@@ -111,6 +157,14 @@
|
||||
revision = "c3e18be99d19e6b3e8f1559eea2c161a665c4b6b"
|
||||
version = "v1.4.1"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:0ade334594e69404d80d9d323445d2297ff8161637f9b2d347cc6973d2d6f05b"
|
||||
name = "github.com/hashicorp/errwrap"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "8a6fb523712970c966eefc6b39ed2c5e74880354"
|
||||
version = "v1.0.0"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:cf6b61e1b4c26b0c7526cee4a0cee6d8302b17798af4b2a56a90eedac0aef11a"
|
||||
name = "github.com/hashicorp/go-hclog"
|
||||
@@ -135,6 +189,14 @@
|
||||
revision = "ad60660ecf9c5a1eae0ca32182ed72bab5807961"
|
||||
version = "v0.5.5"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:f668349b83f7d779567c880550534addeca7ebadfdcf44b0b9c39be61864b4b7"
|
||||
name = "github.com/hashicorp/go-multierror"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "886a7fbe3eb1c874d46f623bfa70af45f425b3d1"
|
||||
version = "v1.0.0"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:7fae9ec96d10b2afce0da23c378c8b3389319b7f92fa092f2621bba3078cfb4b"
|
||||
name = "github.com/hashicorp/golang-lru"
|
||||
@@ -211,6 +273,21 @@
|
||||
revision = "7513a9b590e428674e3c22ea82f46b28890cc17a"
|
||||
version = "v1.0.0"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:4a70938660ae196961d0285062fa7ae5b8abcf1c800f4c750803c06c2150a716"
|
||||
name = "github.com/integration-system/isp-etp-go"
|
||||
packages = [
|
||||
".",
|
||||
"ack",
|
||||
"bpool",
|
||||
"client",
|
||||
"gen",
|
||||
"parser",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "6e92a3dda2cf7c6ec82fc1a1ae922248754e49d9"
|
||||
version = "v2.0.0"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:70304818e3d84deb317b59a0d02fc95c4f4264b8721efa816e97f749d8cf90a1"
|
||||
@@ -309,6 +386,18 @@
|
||||
revision = "de8848e004dd33dc07a2947b3d76f618a7fc7ef1"
|
||||
version = "v1.8.1"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:927762c6729b4e72957ba3310e485ed09cf8451c5a637a52fd016a9fe09e7936"
|
||||
name = "github.com/mailru/easyjson"
|
||||
packages = [
|
||||
"buffer",
|
||||
"jlexer",
|
||||
"jwriter",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "1b2b06f5f209fea48ff5922d8bfb2b9ed5d8f00b"
|
||||
version = "v0.7.0"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:4a29eeb25603debe8f2098a9902c4d3851034cf70d33be428826e86e8c30a1b0"
|
||||
name = "github.com/mattn/go-colorable"
|
||||
@@ -531,7 +620,7 @@
|
||||
revision = "53bf42e6b339f7ed00535fc6915737b3959eac89"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:8d8faad6b12a3a4c819a3f9618cb6ee1fa1cfc33253abeeea8b55336721e3405"
|
||||
digest = "1:66a2f252a58b4fbbad0e4e180e1d85a83c222b6bce09c3dcdef3dc87c72eda7c"
|
||||
name = "golang.org/x/text"
|
||||
packages = [
|
||||
"collate",
|
||||
@@ -550,11 +639,25 @@
|
||||
"unicode/cldr",
|
||||
"unicode/norm",
|
||||
"unicode/rangetable",
|
||||
"width",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "342b2e1fbaa52c93f31447ad2c6abc048c63e475"
|
||||
version = "v0.3.2"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:5b507266031c35e0b72a9cc799ab81ecb876b7014260e5b90537a27cb557729e"
|
||||
name = "golang.org/x/tools"
|
||||
packages = [
|
||||
"go/ast/astutil",
|
||||
"go/buildutil",
|
||||
"go/internal/cgo",
|
||||
"go/loader",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "9cc4af7d6b2c2a2e47f9cfaa500cd669b42e449b"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:a910255c3b706b4d8f2b185ed6b40c8f31b805111be240def2bdf2c62b87591b"
|
||||
@@ -625,19 +728,33 @@
|
||||
source = "https://github.com/mellium/sasl.git"
|
||||
version = "v0.2.1"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:3b259d69525636f66fabb6de37762a0c02e43b20fce972a454eedc6618067133"
|
||||
name = "nhooyr.io/websocket"
|
||||
packages = [
|
||||
".",
|
||||
"internal/bpool",
|
||||
"internal/wsjs",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "8bf88772e1209d96a00bc38276cda458661ebe2b"
|
||||
version = "v1.7.2"
|
||||
|
||||
[solve-meta]
|
||||
analyzer-name = "dep"
|
||||
analyzer-version = 1
|
||||
input-imports = [
|
||||
"github.com/alecthomas/template",
|
||||
"github.com/asaskevich/govalidator",
|
||||
"github.com/cenkalti/backoff",
|
||||
"github.com/go-pg/pg",
|
||||
"github.com/googollee/go-socket.io",
|
||||
"github.com/hashicorp/go-hclog",
|
||||
"github.com/hashicorp/raft",
|
||||
"github.com/hashicorp/raft-boltdb",
|
||||
"github.com/integration-system/bellows",
|
||||
"github.com/integration-system/golang-socketio",
|
||||
"github.com/integration-system/isp-etp-go",
|
||||
"github.com/integration-system/isp-etp-go/client",
|
||||
"github.com/integration-system/isp-lib/backend",
|
||||
"github.com/integration-system/isp-lib/bootstrap",
|
||||
"github.com/integration-system/isp-lib/config",
|
||||
@@ -648,6 +765,7 @@
|
||||
"github.com/integration-system/isp-lib/utils",
|
||||
"github.com/integration-system/isp-log",
|
||||
"github.com/integration-system/isp-log/stdcodes",
|
||||
"github.com/integration-system/swag",
|
||||
"github.com/json-iterator/go",
|
||||
"github.com/mohae/deepcopy",
|
||||
"github.com/pkg/errors",
|
||||
|
||||
@@ -51,5 +51,3 @@
|
||||
[[override]]
|
||||
name = "github.com/hashicorp/raft"
|
||||
branch = "master"
|
||||
|
||||
|
||||
+4
-4
@@ -71,12 +71,12 @@ func (client *Client) SyncApply(command []byte) (*ApplyLogResponse, error) {
|
||||
if client.leaderClient == nil {
|
||||
return nil, ErrLeaderClientNotInitialized
|
||||
}
|
||||
response, err := client.leaderClient.Send(command, defaultApplyTimeout)
|
||||
response, err := client.leaderClient.Ack(command, defaultApplyTimeout)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var logResponse ApplyLogResponse
|
||||
err = json.Unmarshal([]byte(response), &logResponse)
|
||||
err = json.Unmarshal(response, &logResponse)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -119,9 +119,9 @@ func (client *Client) listenLeader() {
|
||||
go func(declaration structure.BackendDeclaration) {
|
||||
response, err := leaderClient.SendDeclaration(declaration, defaultApplyTimeout)
|
||||
if err != nil {
|
||||
log.Warnf(codes.SendDeclarationToLeaderError, "send declaration to leader err: %v", err)
|
||||
log.Warnf(codes.SendDeclarationToLeaderError, "send declaration to leader. err: %v", err)
|
||||
} else if response != Ok {
|
||||
log.Warnf(codes.SendDeclarationToLeaderError, "send declaration to leader response: %s", response)
|
||||
log.Warnf(codes.SendDeclarationToLeaderError, "send declaration to leader. response: %s", response)
|
||||
}
|
||||
}(client.declaration)
|
||||
|
||||
|
||||
+72
-42
@@ -1,9 +1,11 @@
|
||||
package cluster
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/cenkalti/backoff"
|
||||
gosocketio "github.com/integration-system/golang-socketio"
|
||||
etp "github.com/integration-system/isp-etp-go/client"
|
||||
"github.com/integration-system/isp-lib/config"
|
||||
"github.com/integration-system/isp-lib/structure"
|
||||
"github.com/integration-system/isp-lib/utils"
|
||||
@@ -11,20 +13,26 @@ import (
|
||||
"isp-config-service/codes"
|
||||
"isp-config-service/conf"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
LeaderClientReconnectionTimeout = 500 * time.Millisecond
|
||||
)
|
||||
|
||||
type SocketLeaderClient struct {
|
||||
c *gosocketio.Client
|
||||
client etp.Client
|
||||
url string
|
||||
globalCtx context.Context
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func (c *SocketLeaderClient) Send(data []byte, timeout time.Duration) (string, error) {
|
||||
response, err := c.c.Ack(ApplyCommandEvent, string(data), timeout)
|
||||
// REMOVE after replacing socket.io
|
||||
if res, err := strconv.Unquote(response); err == nil {
|
||||
response = res
|
||||
}
|
||||
func (c *SocketLeaderClient) Ack(data []byte, timeout time.Duration) ([]byte, error) {
|
||||
ctx, _ := context.WithTimeout(c.globalCtx, timeout)
|
||||
response, err := c.client.EmitWithAck(ctx, ApplyCommandEvent, data)
|
||||
return response, err
|
||||
}
|
||||
|
||||
@@ -33,52 +41,74 @@ func (c *SocketLeaderClient) SendDeclaration(backend structure.BackendDeclaratio
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if c.c.IsAlive() {
|
||||
response, err := c.c.Ack(utils.ModuleReady, string(data), timeout)
|
||||
// REMOVE after replacing socket.io
|
||||
if res, err := strconv.Unquote(response); err == nil {
|
||||
response = res
|
||||
}
|
||||
return response, err
|
||||
}
|
||||
return "", errors.New("SendDeclaration connection is not alive")
|
||||
ctx, _ := context.WithTimeout(c.globalCtx, timeout)
|
||||
response, err := c.client.EmitWithAck(ctx, utils.ModuleReady, data)
|
||||
return string(response), err
|
||||
}
|
||||
|
||||
func (c *SocketLeaderClient) Dial(timeout time.Duration) error {
|
||||
backOff := backoff.NewExponentialBackOff()
|
||||
backOff.MaxElapsedTime = timeout
|
||||
return backoff.Retry(c.c.Dial, backOff)
|
||||
dial := func() error {
|
||||
return c.client.Dial(context.Background(), c.url)
|
||||
}
|
||||
return backoff.Retry(dial, backOff)
|
||||
}
|
||||
|
||||
func (c *SocketLeaderClient) Close() {
|
||||
c.c.Close()
|
||||
c.cancel()
|
||||
err := c.client.Close()
|
||||
if err != nil {
|
||||
log.Warnf(codes.LeaderClientConnectionError, "leader client close err: %v", err)
|
||||
}
|
||||
log.Debug(0, "leader client connection closed")
|
||||
}
|
||||
|
||||
func NewSocketLeaderClient(address string, leaderDisconnectionCallback func()) *SocketLeaderClient {
|
||||
socketIoAddress := getSocketIoUrl(address)
|
||||
client := gosocketio.NewClientBuilder().
|
||||
EnableReconnection().
|
||||
ReconnectionTimeout(1 * time.Second).
|
||||
OnReconnectionError(func(err error) {
|
||||
log.Warnf(codes.LeaderClientConnectionError, "leader client reconnection err: %v", err)
|
||||
}).
|
||||
BuildToConnect(socketIoAddress)
|
||||
err := client.On(gosocketio.OnDisconnection, func(channel *gosocketio.Channel) {
|
||||
etpConfig := etp.Config{
|
||||
HttpClient: http.DefaultClient,
|
||||
}
|
||||
client := etp.NewClient(etpConfig)
|
||||
leaderClient := &SocketLeaderClient{
|
||||
client: client,
|
||||
url: getUrl(address),
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
leaderClient.globalCtx = ctx
|
||||
leaderClient.cancel = cancel
|
||||
|
||||
leaderClient.client.OnDisconnect(func(err error) {
|
||||
log.WithMetadata(map[string]interface{}{
|
||||
"leaderIp": channel.Ip(),
|
||||
"leaderAddr": address,
|
||||
}).Warn(codes.LeaderClientDisconnected, "leader client disconnected")
|
||||
leaderDisconnectionCallback()
|
||||
go func() {
|
||||
for {
|
||||
err := leaderClient.client.Dial(leaderClient.globalCtx, leaderClient.url)
|
||||
if err == nil {
|
||||
log.Warnf(codes.LeaderClientConnectionError, "leader client reconnected")
|
||||
return
|
||||
} else if errors.Is(err, context.Canceled) {
|
||||
log.Warnf(codes.LeaderClientConnectionError, "leader client reconnection canceled")
|
||||
return
|
||||
} else {
|
||||
log.Warnf(codes.LeaderClientConnectionError, "leader client reconnection err: %v", err)
|
||||
}
|
||||
time.Sleep(LeaderClientReconnectionTimeout)
|
||||
}
|
||||
}()
|
||||
})
|
||||
if err != nil {
|
||||
panic(err) // must never occurred, and will removed in future
|
||||
}
|
||||
|
||||
return &SocketLeaderClient{
|
||||
c: client,
|
||||
}
|
||||
leaderClient.client.OnError(func(err error) {
|
||||
log.Warnf(codes.LeaderClientConnectionError, "leader client on error: %v", err)
|
||||
})
|
||||
leaderClient.client.OnConnect(func() {
|
||||
log.Warnf(codes.LeaderClientConnectionError, "leader client connected")
|
||||
})
|
||||
return leaderClient
|
||||
}
|
||||
|
||||
func getSocketIoUrl(address string) string {
|
||||
func getUrl(address string) string {
|
||||
addr, err := net.ResolveTCPAddr("tcp", address)
|
||||
if err != nil {
|
||||
panic(err) // must never occurred
|
||||
@@ -100,10 +130,10 @@ func getSocketIoUrl(address string) string {
|
||||
// port = 9031
|
||||
//}
|
||||
//
|
||||
return gosocketio.GetUrl(addr.IP.String(), port, false, map[string]string{
|
||||
ClusterParam: "true",
|
||||
"module_name": cfg.ModuleName,
|
||||
// TODO вынести ключи в константы в isp-lib и выпилить instance_uuid
|
||||
"instance_uuid": "9d89354b-c728-4b48-b002-a7d3b229f151",
|
||||
})
|
||||
params := url.Values{}
|
||||
params.Add(ClusterParam, "true")
|
||||
// TODO вынести ключи в константы в isp-lib и выпилить instance_uuid
|
||||
params.Add("module_name", cfg.ModuleName)
|
||||
params.Add("instance_uuid", "9d89354b-c728-4b48-b002-a7d3b229f151")
|
||||
return fmt.Sprintf("ws://%s:%d/isp-etp/?%s", addr.IP.String(), port, params.Encode())
|
||||
}
|
||||
+2
-2
@@ -6,8 +6,8 @@ const (
|
||||
ShutdownHttpServerError = 1002
|
||||
ShutdownHttpServerInfo = 1003
|
||||
|
||||
SocketIoError = 1004
|
||||
SocketIoEmitError = 1005
|
||||
WebsocketError = 1004
|
||||
WebsocketEmitError = 1005
|
||||
|
||||
DatabaseOperationError = 1006
|
||||
|
||||
|
||||
+2
-2
@@ -1,13 +1,13 @@
|
||||
package holder
|
||||
|
||||
import (
|
||||
etp "github.com/integration-system/isp-etp-go"
|
||||
"isp-config-service/cluster"
|
||||
"isp-config-service/ws"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
var (
|
||||
ClusterClient *cluster.Client
|
||||
Socket *ws.WebsocketServer
|
||||
EtpServer etp.Server
|
||||
HttpServer *http.Server
|
||||
)
|
||||
@@ -2,6 +2,7 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/integration-system/isp-etp-go"
|
||||
"github.com/integration-system/isp-lib/backend"
|
||||
"github.com/integration-system/isp-lib/bootstrap"
|
||||
"github.com/integration-system/isp-lib/config"
|
||||
@@ -20,7 +21,6 @@ import (
|
||||
"isp-config-service/store"
|
||||
"isp-config-service/store/state"
|
||||
"isp-config-service/subs"
|
||||
"isp-config-service/ws"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
@@ -51,6 +51,7 @@ func init() {
|
||||
// @host localhost:9003
|
||||
// @BasePath /api/config
|
||||
func main() {
|
||||
ctx := context.Background()
|
||||
cfg := config.Get().(*conf.Configuration)
|
||||
handlers := helper.GetHandlers()
|
||||
endpoints := backend.GetEndpoints(cfg.ModuleName, handlers)
|
||||
@@ -64,10 +65,9 @@ func main() {
|
||||
|
||||
model.DbClient.ReceiveConfiguration(cfg.Database)
|
||||
_, raftStore := initRaft(cfg.WS.Raft.GetAddress(), cfg.Cluster, declaration)
|
||||
initWebsocket(cfg.WS.Rest.GetAddress(), raftStore)
|
||||
initWebsocket(ctx, cfg.WS.Rest.GetAddress(), raftStore)
|
||||
initGrpc(cfg.WS.Grpc, raftStore)
|
||||
|
||||
ctx := context.Background()
|
||||
defer goodbye.Exit(ctx, -1)
|
||||
goodbye.Notify(ctx)
|
||||
goodbye.Register(onShutdown)
|
||||
@@ -75,23 +75,22 @@ func main() {
|
||||
<-shutdownChan
|
||||
}
|
||||
|
||||
func initWebsocket(bindAddress string, raftStore *store.Store) {
|
||||
socket, err := ws.NewWebsocketServer()
|
||||
if err != nil {
|
||||
// TODO уйдет при миграции
|
||||
log.Fatalf(0, "init socket.io %s", err.Error())
|
||||
func initWebsocket(ctx context.Context, bindAddress string, raftStore *store.Store) {
|
||||
etpConfig := etp.ServerConfig{
|
||||
InsecureSkipVerify: true,
|
||||
}
|
||||
subs.NewSocketEventHandler(socket, raftStore).SubscribeAll()
|
||||
etpServer := etp.NewServer(ctx, etpConfig)
|
||||
subs.NewSocketEventHandler(etpServer, raftStore).SubscribeAll()
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/socket.io/", socket.ServeHttp)
|
||||
mux.HandleFunc("/isp-etp/", etpServer.ServeHttp)
|
||||
httpServer := &http.Server{Addr: bindAddress, Handler: mux}
|
||||
go func() {
|
||||
if err := httpServer.ListenAndServe(); err != nil {
|
||||
log.Fatalf(codes.StartHttpServerError, "unable to start http server. %v", err)
|
||||
log.Fatalf(codes.StartHttpServerError, "http server closed: %v", err)
|
||||
}
|
||||
}()
|
||||
holder.Socket = socket
|
||||
holder.EtpServer = etpServer
|
||||
holder.HttpServer = httpServer
|
||||
}
|
||||
|
||||
@@ -161,12 +160,7 @@ func onShutdown(ctx context.Context, sig os.Signal) {
|
||||
log.Info(codes.RaftShutdownInfo, "raft shutdown success")
|
||||
}
|
||||
|
||||
if err := holder.Socket.Close(); err != nil {
|
||||
// TODO уйдет при миграции
|
||||
log.Warnf(0, "socket.io shutdown err: %s", err.Error())
|
||||
} else {
|
||||
log.Info(0, "socket.io shutdown success")
|
||||
}
|
||||
holder.EtpServer.Close()
|
||||
|
||||
if err := holder.HttpServer.Shutdown(ctx); err != nil {
|
||||
log.Warnf(codes.ShutdownHttpServerError, "http server shutdown err: %v", err)
|
||||
|
||||
+5
-5
@@ -32,23 +32,23 @@ func (l *LoggerAdapter) Log(level logrus.Level, msg string, args ...interface{})
|
||||
}
|
||||
|
||||
func (l *LoggerAdapter) Trace(msg string, args ...interface{}) {
|
||||
l.Log(logrus.TraceLevel, msg, args)
|
||||
l.Log(logrus.TraceLevel, msg, args...)
|
||||
}
|
||||
|
||||
func (l *LoggerAdapter) Debug(msg string, args ...interface{}) {
|
||||
l.Log(logrus.DebugLevel, msg, args)
|
||||
l.Log(logrus.DebugLevel, msg, args...)
|
||||
}
|
||||
|
||||
func (l *LoggerAdapter) Info(msg string, args ...interface{}) {
|
||||
l.Log(logrus.InfoLevel, msg, args)
|
||||
l.Log(logrus.InfoLevel, msg, args...)
|
||||
}
|
||||
|
||||
func (l *LoggerAdapter) Warn(msg string, args ...interface{}) {
|
||||
l.Log(logrus.WarnLevel, msg, args)
|
||||
l.Log(logrus.WarnLevel, msg, args...)
|
||||
}
|
||||
|
||||
func (l *LoggerAdapter) Error(msg string, args ...interface{}) {
|
||||
l.Log(logrus.ErrorLevel, msg, args)
|
||||
l.Log(logrus.ErrorLevel, msg, args...)
|
||||
}
|
||||
|
||||
func (l *LoggerAdapter) IsTrace() bool {
|
||||
|
||||
+5
-5
@@ -119,20 +119,20 @@ func (cs configService) BroadcastNewConfig(state state.ReadonlyState, configs ..
|
||||
|
||||
compiledConfig, err := cs.GetCompiledConfig(moduleName, state)
|
||||
if err != nil {
|
||||
go cs.broadcast(room, utils.ConfigError, err.Error())
|
||||
go cs.broadcast(room, utils.ConfigError, []byte(err.Error()))
|
||||
continue
|
||||
}
|
||||
data, err := json.Marshal(compiledConfig)
|
||||
if err != nil {
|
||||
go cs.broadcast(room, utils.ConfigError, err.Error())
|
||||
go cs.broadcast(room, utils.ConfigError, []byte(err.Error()))
|
||||
continue
|
||||
}
|
||||
go cs.broadcast(room, utils.ConfigSendConfigWhenConnected, string(data))
|
||||
go cs.broadcast(room, utils.ConfigSendConfigWhenConnected, data)
|
||||
}
|
||||
}
|
||||
|
||||
func (cs configService) broadcast(room, event, data string) {
|
||||
err := holder.Socket.Broadcast(room, utils.ConfigSendConfigWhenConnected, data)
|
||||
func (cs configService) broadcast(room, event string, data []byte) {
|
||||
err := holder.EtpServer.BroadcastToRoom(room, utils.ConfigSendConfigWhenConnected, data)
|
||||
if err != nil {
|
||||
log.Errorf(codes.ConfigServiceBroadcastConfigError, "broadcast %s err: %v", event, err)
|
||||
}
|
||||
|
||||
+11
-10
@@ -1,15 +1,16 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"github.com/cenkalti/backoff"
|
||||
etp "github.com/integration-system/isp-etp-go"
|
||||
"github.com/integration-system/isp-lib/structure"
|
||||
"github.com/integration-system/isp-lib/utils"
|
||||
log "github.com/integration-system/isp-log"
|
||||
"isp-config-service/codes"
|
||||
"isp-config-service/holder"
|
||||
"isp-config-service/store/state"
|
||||
"isp-config-service/ws"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -32,26 +33,26 @@ func (ds *discoveryService) HandleDisconnect(connId string) {
|
||||
ds.lock.Lock()
|
||||
defer ds.lock.Unlock()
|
||||
if events, ok := ds.subs[connId]; ok {
|
||||
holder.Socket.Rooms().LeaveByConnId(connId, events...)
|
||||
holder.EtpServer.Rooms().LeaveByConnId(connId, events...)
|
||||
delete(ds.subs, connId)
|
||||
}
|
||||
}
|
||||
|
||||
func (ds *discoveryService) Subscribe(conn ws.Conn, events []string, mesh state.ReadonlyMesh) {
|
||||
func (ds *discoveryService) Subscribe(conn etp.Conn, events []string, mesh state.ReadonlyMesh) {
|
||||
if len(events) == 0 {
|
||||
return
|
||||
}
|
||||
ds.lock.Lock()
|
||||
defer ds.lock.Unlock()
|
||||
ds.subs[conn.Id()] = events
|
||||
holder.Socket.Rooms().Join(conn, events...)
|
||||
ds.subs[conn.ID()] = events
|
||||
holder.EtpServer.Rooms().Join(conn, events...)
|
||||
eventsAddresses := make([][]structure.AddressConfiguration, 0, len(events))
|
||||
for _, event := range events {
|
||||
eventName := strings.TrimSuffix(event, ModuleConnectionEventSuffix)
|
||||
addressList := mesh.GetModuleAddresses(eventName)
|
||||
eventsAddresses = append(eventsAddresses, addressList)
|
||||
}
|
||||
go func(events []string, eventsAddresses [][]structure.AddressConfiguration, conn ws.Conn) {
|
||||
go func(events []string, eventsAddresses [][]structure.AddressConfiguration, conn etp.Conn) {
|
||||
for i := range events {
|
||||
event := events[i]
|
||||
addressList := eventsAddresses[i]
|
||||
@@ -76,11 +77,11 @@ func (ds *discoveryService) BroadcastModuleAddresses(moduleName string, mesh sta
|
||||
}(moduleName, event, addressList)
|
||||
}
|
||||
|
||||
func (ds *discoveryService) broadcastAddrList(moduleName string, event string, addressList []structure.AddressConfiguration) error {
|
||||
func (ds *discoveryService) broadcastAddrList(room string, event string, addressList []structure.AddressConfiguration) error {
|
||||
if bytes, err := json.Marshal(addressList); err != nil {
|
||||
return err
|
||||
} else {
|
||||
err = holder.Socket.Broadcast(moduleName, event, string(bytes))
|
||||
err = holder.EtpServer.BroadcastToRoom(room, event, bytes)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -88,13 +89,13 @@ func (ds *discoveryService) broadcastAddrList(moduleName string, event string, a
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ds *discoveryService) sendAddrList(conn ws.Conn, event string, addressList []structure.AddressConfiguration) error {
|
||||
func (ds *discoveryService) sendAddrList(conn etp.Conn, event string, addressList []structure.AddressConfiguration) error {
|
||||
if bytes, err := json.Marshal(addressList); err != nil {
|
||||
return err
|
||||
} else {
|
||||
bf := backoff.WithMaxRetries(backoff.NewConstantBackOff(100*time.Millisecond), 3)
|
||||
err := backoff.Retry(func() error {
|
||||
return conn.Emit(event, string(bytes))
|
||||
return conn.Emit(context.Background(), event, bytes)
|
||||
}, bf)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
+9
-8
@@ -1,15 +1,16 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"github.com/cenkalti/backoff"
|
||||
etp "github.com/integration-system/isp-etp-go"
|
||||
"github.com/integration-system/isp-lib/structure"
|
||||
"github.com/integration-system/isp-lib/utils"
|
||||
log "github.com/integration-system/isp-log"
|
||||
"isp-config-service/codes"
|
||||
"isp-config-service/holder"
|
||||
"isp-config-service/store/state"
|
||||
"isp-config-service/ws"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -22,13 +23,13 @@ var RoutesService routesService
|
||||
type routesService struct{}
|
||||
|
||||
func (rs *routesService) HandleDisconnect(connId string) {
|
||||
holder.Socket.Rooms().LeaveByConnId(connId, RoutesSubscribersRoom)
|
||||
holder.EtpServer.Rooms().LeaveByConnId(connId, RoutesSubscribersRoom)
|
||||
}
|
||||
|
||||
func (rs *routesService) SubscribeRoutes(conn ws.Conn, mesh state.ReadonlyMesh) {
|
||||
holder.Socket.Rooms().Join(conn, RoutesSubscribersRoom)
|
||||
func (rs *routesService) SubscribeRoutes(conn etp.Conn, mesh state.ReadonlyMesh) {
|
||||
holder.EtpServer.Rooms().Join(conn, RoutesSubscribersRoom)
|
||||
routes := mesh.GetRoutes()
|
||||
go func(conn ws.Conn, routes structure.RoutingConfig) {
|
||||
go func(conn etp.Conn, routes structure.RoutingConfig) {
|
||||
err := rs.sendRoutes(conn, utils.ConfigSendRoutesWhenConnected, routes)
|
||||
if err != nil {
|
||||
log.Errorf(codes.RoutesServiceSendRoutesError, "send routes %v", err)
|
||||
@@ -50,7 +51,7 @@ func (rs *routesService) broadcastRoutes(event string, routes structure.RoutingC
|
||||
if bytes, err := json.Marshal(routes); err != nil {
|
||||
return err
|
||||
} else {
|
||||
err = holder.Socket.Broadcast(RoutesSubscribersRoom, event, string(bytes))
|
||||
err = holder.EtpServer.BroadcastToRoom(RoutesSubscribersRoom, event, bytes)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -58,13 +59,13 @@ func (rs *routesService) broadcastRoutes(event string, routes structure.RoutingC
|
||||
return nil
|
||||
}
|
||||
|
||||
func (rs *routesService) sendRoutes(conn ws.Conn, event string, routes structure.RoutingConfig) error {
|
||||
func (rs *routesService) sendRoutes(conn etp.Conn, event string, routes structure.RoutingConfig) error {
|
||||
if bytes, err := json.Marshal(routes); err != nil {
|
||||
return err
|
||||
} else {
|
||||
bf := backoff.WithMaxRetries(backoff.NewConstantBackOff(100*time.Millisecond), 3)
|
||||
err := backoff.Retry(func() error {
|
||||
return conn.Emit(event, string(bytes))
|
||||
return conn.Emit(context.Background(), event, bytes)
|
||||
}, bf)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
+22
-22
@@ -3,6 +3,7 @@ package subs
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/asaskevich/govalidator"
|
||||
etp "github.com/integration-system/isp-etp-go"
|
||||
"github.com/integration-system/isp-lib/bootstrap"
|
||||
schema2 "github.com/integration-system/isp-lib/config/schema"
|
||||
"github.com/integration-system/isp-lib/structure"
|
||||
@@ -11,23 +12,22 @@ import (
|
||||
"isp-config-service/entity"
|
||||
"isp-config-service/service"
|
||||
"isp-config-service/store/state"
|
||||
"isp-config-service/ws"
|
||||
)
|
||||
|
||||
func (h *socketEventHandler) handleModuleReady(conn ws.Conn, data []byte) string {
|
||||
moduleName, _ := conn.Parameters() // REMOVE
|
||||
func (h *socketEventHandler) handleModuleReady(conn etp.Conn, data []byte) []byte {
|
||||
moduleName, _ := Parameters(conn) // REMOVE
|
||||
log.Debugf(0, "handleModuleReady moduleName: %s", moduleName) // REMOVE
|
||||
declaration := structure.BackendDeclaration{}
|
||||
err := json.Unmarshal(data, &declaration)
|
||||
if err != nil {
|
||||
return err.Error()
|
||||
return []byte(err.Error())
|
||||
}
|
||||
|
||||
_, err = govalidator.ValidateStruct(declaration)
|
||||
if err != nil {
|
||||
return err.Error()
|
||||
return []byte(err.Error())
|
||||
}
|
||||
conn.SetBackendDeclaration(declaration)
|
||||
SetBackendDeclaration(conn, declaration)
|
||||
var changed bool
|
||||
h.store.VisitReadonlyState(func(state state.ReadonlyState) {
|
||||
changed = state.Mesh().CheckBackendChanged(declaration)
|
||||
@@ -36,23 +36,23 @@ func (h *socketEventHandler) handleModuleReady(conn ws.Conn, data []byte) string
|
||||
command := cluster.PrepareUpdateBackendDeclarationCommand(declaration)
|
||||
_, err = SyncApplyCommand(command, "UpdateBackendDeclarationCommand")
|
||||
if err != nil {
|
||||
return err.Error()
|
||||
return []byte(err.Error())
|
||||
}
|
||||
}
|
||||
return Ok
|
||||
return []byte(Ok)
|
||||
}
|
||||
|
||||
func (h *socketEventHandler) handleModuleRequirements(conn ws.Conn, data []byte) string {
|
||||
moduleName, err := conn.Parameters()
|
||||
func (h *socketEventHandler) handleModuleRequirements(conn etp.Conn, data []byte) []byte {
|
||||
moduleName, err := Parameters(conn)
|
||||
log.Debugf(0, "handleModuleRequirements moduleName: %s", moduleName) // REMOVE
|
||||
if err != nil {
|
||||
return err.Error()
|
||||
return []byte(err.Error())
|
||||
}
|
||||
|
||||
declaration := bootstrap.ModuleRequirements{}
|
||||
err = json.Unmarshal(data, &declaration)
|
||||
if err != nil {
|
||||
return err.Error()
|
||||
return []byte(err.Error())
|
||||
}
|
||||
|
||||
h.store.VisitReadonlyState(func(state state.ReadonlyState) {
|
||||
@@ -61,19 +61,19 @@ func (h *socketEventHandler) handleModuleRequirements(conn ws.Conn, data []byte)
|
||||
service.RoutesService.SubscribeRoutes(conn, state.Mesh())
|
||||
}
|
||||
})
|
||||
return Ok
|
||||
return []byte(Ok)
|
||||
}
|
||||
|
||||
func (h *socketEventHandler) handleConfigSchema(conn ws.Conn, data []byte) string {
|
||||
moduleName, err := conn.Parameters()
|
||||
func (h *socketEventHandler) handleConfigSchema(conn etp.Conn, data []byte) []byte {
|
||||
moduleName, err := Parameters(conn)
|
||||
log.Debugf(0, "handleConfigSchema moduleName: %s", moduleName) // REMOVE
|
||||
if err != nil {
|
||||
return err.Error()
|
||||
return []byte(err.Error())
|
||||
}
|
||||
|
||||
configSchema := schema2.ConfigSchema{}
|
||||
if err := json.Unmarshal(data, &configSchema); err != nil {
|
||||
return err.Error()
|
||||
return []byte(err.Error())
|
||||
}
|
||||
// TODO Костыль. Дважды посылаем ModuleConnected, т.к с момента первой отправки в handleConnect,
|
||||
// состояние к конкретной ноде кластера может не успеть примениться
|
||||
@@ -87,7 +87,7 @@ func (h *socketEventHandler) handleConfigSchema(conn ws.Conn, data []byte) strin
|
||||
command := cluster.PrepareModuleConnectedCommand(newModule)
|
||||
_, err = SyncApplyCommand(command, "ModuleConnectedCommand")
|
||||
if err != nil {
|
||||
return err.Error()
|
||||
return []byte(err.Error())
|
||||
}
|
||||
// />
|
||||
|
||||
@@ -96,7 +96,7 @@ func (h *socketEventHandler) handleConfigSchema(conn ws.Conn, data []byte) strin
|
||||
module = readState.Modules().GetByName(moduleName)
|
||||
})
|
||||
if module == nil {
|
||||
return fmt.Sprintf("module with name %s not found", moduleName)
|
||||
return []byte(fmt.Sprintf("module with name %s not found", moduleName))
|
||||
}
|
||||
|
||||
schema := entity.ConfigSchema{
|
||||
@@ -131,9 +131,9 @@ func (h *socketEventHandler) handleConfigSchema(conn ws.Conn, data []byte) strin
|
||||
command := cluster.PrepareUpsertConfigCommand(upsertConfig)
|
||||
_, _ = SyncApplyCommand(command, "UpsertConfigCommand")
|
||||
}
|
||||
return Ok
|
||||
return []byte(Ok)
|
||||
}
|
||||
|
||||
func (h *socketEventHandler) handleRequestConfig(conn ws.Conn, data []byte) {
|
||||
|
||||
func (h *socketEventHandler) handleRequestConfig(conn etp.Conn, data []byte) []byte {
|
||||
panic("not implemented")
|
||||
}
|
||||
+4
-4
@@ -1,14 +1,14 @@
|
||||
package subs
|
||||
|
||||
import (
|
||||
etp "github.com/integration-system/isp-etp-go"
|
||||
log "github.com/integration-system/isp-log"
|
||||
"isp-config-service/cluster"
|
||||
"isp-config-service/codes"
|
||||
"isp-config-service/holder"
|
||||
"isp-config-service/ws"
|
||||
)
|
||||
|
||||
func (h *socketEventHandler) applyCommandOnLeader(conn ws.Conn, cmd []byte) string {
|
||||
func (h *socketEventHandler) applyCommandOnLeader(conn etp.Conn, cmd []byte) []byte {
|
||||
obj, err := holder.ClusterClient.SyncApplyOnLeader(cmd)
|
||||
if err != nil {
|
||||
var logResponse cluster.ApplyLogResponse
|
||||
@@ -17,11 +17,11 @@ func (h *socketEventHandler) applyCommandOnLeader(conn ws.Conn, cmd []byte) stri
|
||||
if err != nil {
|
||||
log.Fatalf(codes.SyncApplyError, "marshaling ApplyLogResponse: %v", err)
|
||||
}
|
||||
return string(data)
|
||||
return data
|
||||
}
|
||||
data, err := json.Marshal(obj)
|
||||
if err != nil {
|
||||
log.Fatalf(codes.SyncApplyError, "marshaling ApplyLogResponse: %v", err)
|
||||
}
|
||||
return string(data)
|
||||
return data
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package subs
|
||||
|
||||
import (
|
||||
etp "github.com/integration-system/isp-etp-go"
|
||||
"github.com/integration-system/isp-lib/structure"
|
||||
"github.com/integration-system/isp-lib/utils"
|
||||
"isp-config-service/cluster"
|
||||
)
|
||||
|
||||
type connectionState struct {
|
||||
declaration structure.BackendDeclaration
|
||||
}
|
||||
|
||||
func IsConfigClusterNode(conn etp.Conn) bool {
|
||||
isCluster := conn.URL().Query().Get(cluster.ClusterParam)
|
||||
return isCluster == "true"
|
||||
|
||||
}
|
||||
|
||||
func Parameters(conn etp.Conn) (moduleName string, err error) {
|
||||
// TODO remove instanceUUID from isp-lib
|
||||
_, moduleName, err = utils.ParseParameters(conn.URL().RawQuery)
|
||||
return moduleName, err
|
||||
}
|
||||
|
||||
func SetBackendDeclaration(conn etp.Conn, backend structure.BackendDeclaration) {
|
||||
conn.SetContext(connectionState{declaration: backend})
|
||||
}
|
||||
|
||||
func ExtractBackendDeclaration(conn etp.Conn) (structure.BackendDeclaration, bool) {
|
||||
declaration, ok := conn.Context().(connectionState)
|
||||
return declaration.declaration, ok
|
||||
}
|
||||
+5
-4
@@ -1,19 +1,20 @@
|
||||
package subs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
etp "github.com/integration-system/isp-etp-go"
|
||||
log "github.com/integration-system/isp-log"
|
||||
"isp-config-service/codes"
|
||||
"isp-config-service/holder"
|
||||
"isp-config-service/ws"
|
||||
)
|
||||
|
||||
func EmitConn(conn ws.Conn, event string, args ...interface{}) {
|
||||
err := conn.Emit(event, args...)
|
||||
func EmitConn(conn etp.Conn, event string, body []byte) {
|
||||
err := conn.Emit(context.Background(), event, body)
|
||||
if err != nil {
|
||||
log.WithMetadata(map[string]interface{}{
|
||||
"event": event,
|
||||
}).Warnf(codes.SocketIoEmitError, "emit err %v", err)
|
||||
}).Warnf(codes.WebsocketEmitError, "emit err %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+32
-31
@@ -1,6 +1,7 @@
|
||||
package subs
|
||||
|
||||
import (
|
||||
etp "github.com/integration-system/isp-etp-go"
|
||||
"github.com/integration-system/isp-lib/utils"
|
||||
log "github.com/integration-system/isp-log"
|
||||
jsoniter "github.com/json-iterator/go"
|
||||
@@ -11,12 +12,11 @@ import (
|
||||
"isp-config-service/service"
|
||||
"isp-config-service/store"
|
||||
"isp-config-service/store/state"
|
||||
"isp-config-service/ws"
|
||||
)
|
||||
|
||||
const (
|
||||
Ok = "ok"
|
||||
followersRoom = "followers"
|
||||
followersRoom = "cluster_followers"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -24,12 +24,12 @@ var (
|
||||
)
|
||||
|
||||
type socketEventHandler struct {
|
||||
socket *ws.WebsocketServer
|
||||
server etp.Server
|
||||
store *store.Store
|
||||
}
|
||||
|
||||
func (h *socketEventHandler) SubscribeAll() {
|
||||
h.socket.
|
||||
h.server.
|
||||
OnConnect(h.handleConnect).
|
||||
OnDisconnect(h.handleDisconnect).
|
||||
OnError(h.handleError).
|
||||
@@ -39,18 +39,19 @@ func (h *socketEventHandler) SubscribeAll() {
|
||||
OnWithAck(utils.ModuleSendConfigSchema, h.handleConfigSchema)
|
||||
}
|
||||
|
||||
func (h *socketEventHandler) handleConnect(conn ws.Conn) {
|
||||
if conn.IsConfigClusterNode() {
|
||||
holder.Socket.Rooms().Join(conn, followersRoom)
|
||||
func (h *socketEventHandler) handleConnect(conn etp.Conn) {
|
||||
isClusterNode := IsConfigClusterNode(conn)
|
||||
if isClusterNode {
|
||||
holder.EtpServer.Rooms().Join(conn, followersRoom)
|
||||
}
|
||||
moduleName, err := conn.Parameters()
|
||||
moduleName, err := Parameters(conn)
|
||||
log.Debugf(0, "handleConnect: %s", moduleName) // REMOVE
|
||||
if err != nil {
|
||||
EmitConn(conn, utils.ErrorConnection, err.Error())
|
||||
conn.Disconnect()
|
||||
EmitConn(conn, utils.ErrorConnection, []byte(err.Error()))
|
||||
_ = conn.Close()
|
||||
return
|
||||
}
|
||||
holder.Socket.Rooms().Join(conn, moduleName+service.ConfigWatchersRoomSuffix)
|
||||
holder.EtpServer.Rooms().Join(conn, moduleName+service.ConfigWatchersRoomSuffix)
|
||||
now := state.GenerateDate()
|
||||
module := entity.Module{
|
||||
Id: state.GenerateId(),
|
||||
@@ -60,9 +61,9 @@ func (h *socketEventHandler) handleConnect(conn ws.Conn) {
|
||||
}
|
||||
command := cluster.PrepareModuleConnectedCommand(module)
|
||||
_, err = SyncApplyCommand(command, "ModuleConnectedCommand")
|
||||
if err != nil {
|
||||
EmitConn(conn, utils.ErrorConnection, err.Error())
|
||||
conn.Disconnect()
|
||||
if err != nil && !isClusterNode {
|
||||
EmitConn(conn, utils.ErrorConnection, []byte(err.Error()))
|
||||
_ = conn.Close()
|
||||
return
|
||||
}
|
||||
|
||||
@@ -71,25 +72,25 @@ func (h *socketEventHandler) handleConnect(conn ws.Conn) {
|
||||
config, err = service.ConfigService.GetCompiledConfig(moduleName, state)
|
||||
})
|
||||
if err != nil {
|
||||
EmitConn(conn, utils.ConfigError, err.Error())
|
||||
EmitConn(conn, utils.ConfigError, []byte(err.Error()))
|
||||
return
|
||||
}
|
||||
data, err := json.Marshal(config)
|
||||
if err != nil {
|
||||
EmitConn(conn, utils.ConfigError, err.Error())
|
||||
EmitConn(conn, utils.ConfigError, []byte(err.Error()))
|
||||
return
|
||||
}
|
||||
EmitConn(conn, utils.ConfigSendConfigWhenConnected, string(data))
|
||||
EmitConn(conn, utils.ConfigSendConfigWhenConnected, data)
|
||||
}
|
||||
|
||||
func (h *socketEventHandler) handleDisconnect(conn ws.Conn) {
|
||||
if conn.IsConfigClusterNode() {
|
||||
holder.Socket.Rooms().Leave(conn, followersRoom)
|
||||
func (h *socketEventHandler) handleDisconnect(conn etp.Conn, disconnectErr error) {
|
||||
if IsConfigClusterNode(conn) {
|
||||
holder.EtpServer.Rooms().Leave(conn, followersRoom)
|
||||
}
|
||||
moduleName, _ := conn.Parameters()
|
||||
moduleName, _ := Parameters(conn)
|
||||
log.Debugf(0, "handleDisconnect: %s", moduleName) // REMOVE
|
||||
if moduleName != "" {
|
||||
holder.Socket.Rooms().Leave(conn, moduleName+service.ConfigWatchersRoomSuffix)
|
||||
holder.EtpServer.Rooms().Leave(conn, moduleName+service.ConfigWatchersRoomSuffix)
|
||||
now := state.GenerateDate()
|
||||
module := entity.Module{
|
||||
Id: state.GenerateId(),
|
||||
@@ -102,22 +103,22 @@ func (h *socketEventHandler) handleDisconnect(conn ws.Conn) {
|
||||
_, _ = SyncApplyCommand(command, "ModuleDisconnectedCommand")
|
||||
|
||||
}
|
||||
service.DiscoveryService.HandleDisconnect(conn.Id())
|
||||
service.RoutesService.HandleDisconnect(conn.Id())
|
||||
backend := conn.GetBackendDeclaration()
|
||||
if backend != nil {
|
||||
command := cluster.PrepareDeleteBackendDeclarationCommand(*backend)
|
||||
service.DiscoveryService.HandleDisconnect(conn.ID())
|
||||
service.RoutesService.HandleDisconnect(conn.ID())
|
||||
backend, ok := ExtractBackendDeclaration(conn)
|
||||
if ok {
|
||||
command := cluster.PrepareDeleteBackendDeclarationCommand(backend)
|
||||
_, _ = SyncApplyCommand(command, "DeleteBackendDeclarationCommand")
|
||||
}
|
||||
}
|
||||
|
||||
func (h *socketEventHandler) handleError(conn ws.Conn, err error) {
|
||||
log.Warnf(codes.SocketIoError, "socket.io: %v", err)
|
||||
func (h *socketEventHandler) handleError(conn etp.Conn, err error) {
|
||||
log.Warnf(codes.WebsocketError, "isp-etp: %v", err)
|
||||
}
|
||||
|
||||
func NewSocketEventHandler(socket *ws.WebsocketServer, store *store.Store) *socketEventHandler {
|
||||
func NewSocketEventHandler(server etp.Server, store *store.Store) *socketEventHandler {
|
||||
return &socketEventHandler{
|
||||
socket: socket,
|
||||
server: server,
|
||||
store: store,
|
||||
}
|
||||
}
|
||||
-54
@@ -1,54 +0,0 @@
|
||||
package ws
|
||||
|
||||
import (
|
||||
socketio "github.com/googollee/go-socket.io"
|
||||
"github.com/integration-system/isp-lib/structure"
|
||||
"github.com/integration-system/isp-lib/utils"
|
||||
"isp-config-service/cluster"
|
||||
)
|
||||
|
||||
type Conn interface {
|
||||
Id() string
|
||||
Disconnect()
|
||||
Parameters() (moduleName string, err error)
|
||||
Emit(event string, args ...interface{}) error
|
||||
IsConfigClusterNode() bool
|
||||
SetBackendDeclaration(backend structure.BackendDeclaration)
|
||||
GetBackendDeclaration() *structure.BackendDeclaration
|
||||
}
|
||||
|
||||
type wsConn struct {
|
||||
conn socketio.Socket
|
||||
backend *structure.BackendDeclaration
|
||||
}
|
||||
|
||||
func (c *wsConn) Parameters() (moduleName string, err error) {
|
||||
// TODO remove instanceUUID from isp-lib
|
||||
_, moduleName, err = utils.ParseParameters(c.conn.Request().URL.RawQuery)
|
||||
return moduleName, err
|
||||
}
|
||||
|
||||
func (c *wsConn) Id() string {
|
||||
return c.conn.Id()
|
||||
}
|
||||
|
||||
func (c *wsConn) Disconnect() {
|
||||
c.conn.Disconnect()
|
||||
}
|
||||
|
||||
func (c *wsConn) Emit(event string, args ...interface{}) error {
|
||||
return c.conn.Emit(event, args...)
|
||||
}
|
||||
|
||||
func (c *wsConn) IsConfigClusterNode() bool {
|
||||
isCluster := c.conn.Request().URL.Query().Get(cluster.ClusterParam)
|
||||
return isCluster == "true"
|
||||
}
|
||||
|
||||
func (c *wsConn) SetBackendDeclaration(backend structure.BackendDeclaration) {
|
||||
c.backend = &backend
|
||||
}
|
||||
|
||||
func (c *wsConn) GetBackendDeclaration() *structure.BackendDeclaration {
|
||||
return c.backend
|
||||
}
|
||||
-101
@@ -1,101 +0,0 @@
|
||||
package ws
|
||||
|
||||
import (
|
||||
"sync"
|
||||
)
|
||||
|
||||
const (
|
||||
idsRoom = "__id"
|
||||
)
|
||||
|
||||
type RoomStore struct {
|
||||
mu sync.RWMutex
|
||||
rooms map[string]map[string]Conn
|
||||
}
|
||||
|
||||
func (s *RoomStore) GetOrJoinById(id string, new Conn) Conn {
|
||||
s.mu.RLock()
|
||||
var (
|
||||
conn Conn
|
||||
ok bool
|
||||
)
|
||||
idRoom, roomExist := s.rooms[idsRoom]
|
||||
if roomExist {
|
||||
conn, ok = idRoom[id]
|
||||
}
|
||||
s.mu.RUnlock()
|
||||
if ok {
|
||||
return conn
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
idRoom, roomExist = s.rooms[idsRoom]
|
||||
if roomExist {
|
||||
conn, ok = idRoom[id]
|
||||
}
|
||||
if ok {
|
||||
return conn
|
||||
}
|
||||
conn = new
|
||||
if !roomExist {
|
||||
s.rooms[idsRoom] = map[string]Conn{conn.Id(): conn}
|
||||
return conn
|
||||
}
|
||||
idRoom[conn.Id()] = conn
|
||||
return conn
|
||||
}
|
||||
|
||||
func (s *RoomStore) Join(conn Conn, rooms ...string) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
for _, room := range rooms {
|
||||
if conns, ok := s.rooms[room]; ok {
|
||||
conns[conn.Id()] = conn
|
||||
} else {
|
||||
s.rooms[room] = map[string]Conn{conn.Id(): conn}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *RoomStore) Leave(conn Conn, rooms ...string) {
|
||||
s.LeaveByConnId(conn.Id(), rooms...)
|
||||
}
|
||||
|
||||
func (s *RoomStore) LeaveByConnId(id string, rooms ...string) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
for _, room := range rooms {
|
||||
if conns, ok := s.rooms[room]; ok {
|
||||
delete(conns, id)
|
||||
if len(conns) == 0 {
|
||||
delete(s.rooms, room)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *RoomStore) ToBroadcast(rooms ...string) []Conn {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
result := make([]Conn, 0)
|
||||
for _, room := range rooms {
|
||||
if conns, ok := s.rooms[room]; ok {
|
||||
for _, conn := range conns {
|
||||
result = append(result, conn)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func NewRoomStore() *RoomStore {
|
||||
return &RoomStore{
|
||||
mu: sync.RWMutex{},
|
||||
rooms: make(map[string]map[string]Conn),
|
||||
}
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
package ws
|
||||
|
||||
import (
|
||||
"github.com/googollee/go-socket.io"
|
||||
gosocketio "github.com/integration-system/golang-socketio"
|
||||
"github.com/integration-system/isp-lib/logger"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type WebsocketServer struct {
|
||||
s *socketio.Server
|
||||
roomStore *RoomStore
|
||||
}
|
||||
|
||||
func (s *WebsocketServer) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *WebsocketServer) ServeHttp(w http.ResponseWriter, r *http.Request) {
|
||||
s.s.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
func (s *WebsocketServer) Rooms() *RoomStore {
|
||||
return s.roomStore
|
||||
}
|
||||
|
||||
func (s *WebsocketServer) OnWithAck(event string, f func(conn Conn, data []byte) string) *WebsocketServer {
|
||||
must(s.s.On(event, func(conn socketio.Socket, data string) string {
|
||||
logger.Debugf("[%s]:%s:%s", conn.Request().RemoteAddr, event, data)
|
||||
|
||||
return f(s.roomStore.GetOrJoinById(conn.Id(), &wsConn{conn: conn}), []byte(data))
|
||||
}))
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *WebsocketServer) On(event string, f func(conn Conn, data []byte)) *WebsocketServer {
|
||||
must(s.s.On(event, func(conn socketio.Socket, data []byte) {
|
||||
logger.Debugf("[%s]:%s:%s", conn.Request().RemoteAddr, event, string(data))
|
||||
|
||||
f(s.roomStore.GetOrJoinById(conn.Id(), &wsConn{conn: conn}), data)
|
||||
}))
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *WebsocketServer) OnConnect(f func(Conn)) *WebsocketServer {
|
||||
must(s.s.On(gosocketio.OnConnection, func(conn socketio.Socket) {
|
||||
logger.Debugf("[%s]:%s", conn.Request().RemoteAddr, gosocketio.OnConnection)
|
||||
|
||||
f(s.roomStore.GetOrJoinById(conn.Id(), &wsConn{conn: conn}))
|
||||
}))
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *WebsocketServer) OnDisconnect(f func(Conn)) *WebsocketServer {
|
||||
must(s.s.On(gosocketio.OnDisconnection, func(conn socketio.Socket) {
|
||||
logger.Debugf("[%s]:%s", conn.Request().RemoteAddr, gosocketio.OnDisconnection)
|
||||
|
||||
c := s.roomStore.GetOrJoinById(conn.Id(), &wsConn{conn: conn})
|
||||
f(c)
|
||||
s.roomStore.Leave(c, idsRoom)
|
||||
}))
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *WebsocketServer) OnError(f func(Conn, error)) *WebsocketServer {
|
||||
must(s.s.On(gosocketio.OnError, func(conn socketio.Socket, err error) {
|
||||
logger.Debugf("[%s]:%s:%v", conn.Request().RemoteAddr, gosocketio.OnError, err)
|
||||
|
||||
f(s.roomStore.GetOrJoinById(conn.Id(), &wsConn{conn: conn}), err)
|
||||
}))
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *WebsocketServer) Broadcast(room string, msg string, v ...interface{}) error {
|
||||
conns := s.roomStore.ToBroadcast(room)
|
||||
for _, conn := range conns {
|
||||
err := conn.Emit(msg, v...)
|
||||
if err != nil {
|
||||
logger.Warnf("Broadcast to %s, message %s. err: %v", room, msg, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewWebsocketServer() (*WebsocketServer, error) {
|
||||
server, err := socketio.NewServer(nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &WebsocketServer{
|
||||
s: server,
|
||||
roomStore: NewRoomStore(),
|
||||
}, nil
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
package ws
|
||||
|
||||
func must(err error) {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user