Clean phantom backends
This commit is contained in:
1 parent
1342f0dcf2
commit
7aa2805f4c
22 files changed
+397
-155
No files matched your search
+39
-19
@@ -1,13 +1,15 @@
|
||||
package assembly
|
||||
|
||||
import (
|
||||
"context"
|
||||
"isp-config-service/conf"
|
||||
"isp-config-service/service/module/backend"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/etp/v3"
|
||||
"github.com/txix-open/etp/v4"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/endpoint"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
@@ -24,10 +26,11 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
wsReadLimit = 4 * 1024 * 1024
|
||||
handleEventsInterval = 500 * time.Millisecond
|
||||
cleanEventInterval = 60 * time.Second
|
||||
eventTtl = 60 * time.Second
|
||||
wsReadLimit = 4 * 1024 * 1024
|
||||
handleEventsInterval = 500 * time.Millisecond
|
||||
cleanEventInterval = 60 * time.Second
|
||||
cleanPhantomBackendsInterval = 5 * time.Minute
|
||||
eventTtl = 60 * time.Second
|
||||
)
|
||||
|
||||
type LocalConfig struct {
|
||||
@@ -46,6 +49,10 @@ type LeaderChecker interface {
|
||||
IsLeader() bool
|
||||
}
|
||||
|
||||
type OwnBackendsCleaner interface {
|
||||
DeleteOwnBackends(ctx context.Context)
|
||||
}
|
||||
|
||||
func NewLocator(
|
||||
db db.DB,
|
||||
leaderChecker LeaderChecker,
|
||||
@@ -61,15 +68,17 @@ func NewLocator(
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
GrpcMux *grpc.Mux
|
||||
HttpMux http.Handler
|
||||
EtpSrv *etp.Server
|
||||
HandleEventWorker *worker.Worker
|
||||
CleanEventWorker *worker.Worker
|
||||
GrpcMux *grpc.Mux
|
||||
HttpMux http.Handler
|
||||
EtpSrv *etp.Server
|
||||
HandleEventWorker *worker.Worker
|
||||
CleanEventWorker *worker.Worker
|
||||
CleanPhantomBackendWorker *worker.Worker
|
||||
OwnBackendsCleaner OwnBackendsCleaner
|
||||
}
|
||||
|
||||
//nolint:funlen
|
||||
func (l Locator) Config() Config {
|
||||
func (l Locator) Config() *Config {
|
||||
moduleRepo := repository.NewModule(l.db)
|
||||
backendRepo := repository.NewBackend(l.db)
|
||||
eventRepo := repository.NewEvent(l.db)
|
||||
@@ -93,10 +102,19 @@ func (l Locator) Config() Config {
|
||||
l.logger,
|
||||
)
|
||||
|
||||
moduleService := module.NewService(
|
||||
moduleRepo,
|
||||
backendService := backend.NewBackend(
|
||||
backendRepo,
|
||||
eventRepo,
|
||||
l.cfg.Local.Rqlite.NodeId,
|
||||
etpSrv.Rooms(),
|
||||
l.logger,
|
||||
)
|
||||
cleanPhantomBackendJob := backend.NewCleaner(backendService, l.logger)
|
||||
cleanPhantomBackendWorker := worker.New(cleanPhantomBackendJob, worker.WithInterval(cleanPhantomBackendsInterval))
|
||||
|
||||
moduleService := module.NewService(
|
||||
moduleRepo,
|
||||
backendService,
|
||||
configRepo,
|
||||
configSchemaRepo,
|
||||
subscriptionService,
|
||||
@@ -149,11 +167,13 @@ func (l Locator) Config() Config {
|
||||
cleanerJob := event.NewCleaner(eventRepo, l.leaderChecker, eventTtl, l.logger)
|
||||
cleanEventWorker := worker.New(cleanerJob, worker.WithInterval(cleanEventInterval))
|
||||
|
||||
return Config{
|
||||
GrpcMux: grpcMux,
|
||||
EtpSrv: etpSrv,
|
||||
HttpMux: httpMux,
|
||||
HandleEventWorker: handleEventWorker,
|
||||
CleanEventWorker: cleanEventWorker,
|
||||
return &Config{
|
||||
GrpcMux: grpcMux,
|
||||
EtpSrv: etpSrv,
|
||||
HttpMux: httpMux,
|
||||
HandleEventWorker: handleEventWorker,
|
||||
CleanEventWorker: cleanEventWorker,
|
||||
CleanPhantomBackendWorker: cleanPhantomBackendWorker,
|
||||
OwnBackendsCleaner: backendService,
|
||||
}
|
||||
}
|
||||
@@ -1,2 +1,6 @@
|
||||
## v3.1.0
|
||||
* добавлено возможность анонсировать несколько бекендов с одинаковыми адресами
|
||||
* реализован механизм поиска и очистки фантомных бекендов (те который отключились, но остались висеть в таблице маршрутизации)
|
||||
* добавлена очистка таблицы маршрутизации в момент отключения самого модуля
|
||||
## v3.0.2
|
||||
* Новая реализация модуля на базе rqlite
|
||||
+2
-2
@@ -9,7 +9,7 @@ require (
|
||||
github.com/mattn/go-sqlite3 v1.14.22
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/pressly/goose/v3 v3.22.1
|
||||
github.com/txix-open/isp-kit v1.39.0
|
||||
github.com/txix-open/isp-kit v1.39.1
|
||||
isp-config-service v0.0.0-00010101000000-000000000000
|
||||
)
|
||||
|
||||
@@ -50,7 +50,7 @@ require (
|
||||
github.com/tidwall/match v1.1.1 // indirect
|
||||
github.com/tidwall/pretty v1.2.1 // indirect
|
||||
github.com/txix-open/bellows v1.2.0 // indirect
|
||||
github.com/txix-open/etp/v3 v3.2.0 // indirect
|
||||
github.com/txix-open/etp/v4 v4.0.1 // indirect
|
||||
github.com/txix-open/validator/v10 v10.0.0-20240401163703-e83541b40f99 // indirect
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.56.0 // indirect
|
||||
go.opentelemetry.io/otel v1.31.0 // indirect
|
||||
|
||||
+4
-4
@@ -140,10 +140,10 @@ github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
|
||||
github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
|
||||
github.com/txix-open/bellows v1.2.0 h1:CXv8nQaZtB/micraeRilYyj/gtfv+bqBgP5aPYQgjeY=
|
||||
github.com/txix-open/bellows v1.2.0/go.mod h1:qbKCy+RTgD30Qpw1fyb3y3jp5Y9mGhLLxgae1l0W92o=
|
||||
github.com/txix-open/etp/v3 v3.2.0 h1:EgTchT8VtCYV1iEo/y4jII3/NybrXiQDE0y6pmS350M=
|
||||
github.com/txix-open/etp/v3 v3.2.0/go.mod h1:lgen0TJmiturgBhvlxH1/PQ7iLL/OebKbxPAQYkuKI0=
|
||||
github.com/txix-open/isp-kit v1.39.0 h1:NBV2oJJefH/qt2pcPrqEmYccJedjPaVCwr6Z955C+pg=
|
||||
github.com/txix-open/isp-kit v1.39.0/go.mod h1:R4vwujGjMXLQir8MDDCfsDQa0CWGuZBSMakt5qcybgM=
|
||||
github.com/txix-open/etp/v4 v4.0.1 h1:5VSYgGsvnMz0tvUHsjVWFETI0qWBTCF1O3ARCHaCIgA=
|
||||
github.com/txix-open/etp/v4 v4.0.1/go.mod h1:FIu7TUDdwcgmtmF6tFTV1bGA2fRY/iVaPQdsGzvqYc8=
|
||||
github.com/txix-open/isp-kit v1.39.1 h1:10zEILNQSPY7naiuaQkIKNS2/fnWxuE9bz+dTiAptXw=
|
||||
github.com/txix-open/isp-kit v1.39.1/go.mod h1:xB6mkoOewZBI1ND8kjU5TR6kvLu3VQI3Rdkh6g6FE4I=
|
||||
github.com/txix-open/validator/v10 v10.0.0-20240401163703-e83541b40f99 h1:Z0Sqf+U+Sc6hfIXtRCIZlbJprkCjwMFbS4ZbEPQ44To=
|
||||
github.com/txix-open/validator/v10 v10.0.0-20240401163703-e83541b40f99/go.mod h1:pA0NYmhL0uEkkxj55S+S7MZU4e2QIt46x9XSrzrWc3c=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.56.0 h1:4BZHA+B1wXEQoGNHxW8mURaLhcdGwvRnmhGbm+odRbc=
|
||||
|
||||
@@ -11,4 +11,9 @@ type Local struct {
|
||||
Credentials []auth.Credential
|
||||
KeepConfigVersions int `validate:"required"`
|
||||
InternalClientCredential string `validate:"required"`
|
||||
Rqlite Rqlite
|
||||
}
|
||||
|
||||
type Rqlite struct {
|
||||
NodeId string `validate:"required"`
|
||||
}
|
||||
@@ -2,10 +2,10 @@ package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/txix-open/etp/v4"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/etp/v3"
|
||||
"github.com/txix-open/etp/v3/msg"
|
||||
"github.com/txix-open/etp/v4/msg"
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
|
||||
+10
-9
@@ -6,13 +6,14 @@ import (
|
||||
)
|
||||
|
||||
type Backend struct {
|
||||
ModuleId string `json:"module_id"`
|
||||
Address string `json:"address"`
|
||||
Version string `json:"version"`
|
||||
LibVersion string `json:"lib_version"`
|
||||
ModuleName string `json:"module_name"`
|
||||
Endpoints xtypes.Json[[]cluster.EndpointDescriptor] `json:"endpoints"`
|
||||
RequiredModules xtypes.Json[[]cluster.ModuleDependency] `json:"required_modules"`
|
||||
CreatedAt xtypes.Time `json:"created_at"`
|
||||
UpdatedAt xtypes.Time `json:"updated_at"`
|
||||
WsConnectionId string `json:"ws_connection_id"`
|
||||
ModuleId string `json:"module_id"`
|
||||
Address string `json:"address"`
|
||||
Version string `json:"version"`
|
||||
LibVersion string `json:"lib_version"`
|
||||
ModuleName string `json:"module_name"`
|
||||
ConfigServiceNodeId string `json:"config_service_node_id"`
|
||||
Endpoints xtypes.Json[[]cluster.EndpointDescriptor] `json:"endpoints"`
|
||||
RequiredModules xtypes.Json[[]cluster.ModuleDependency] `json:"required_modules"`
|
||||
CreatedAt xtypes.Time `json:"created_at"`
|
||||
}
|
||||
@@ -9,11 +9,11 @@ require (
|
||||
github.com/pressly/goose/v3 v3.22.1
|
||||
github.com/prometheus/client_golang v1.20.5
|
||||
github.com/rqlite/gorqlite v0.0.0-20241013203532-4385768ae85d
|
||||
github.com/rqlite/rqlite/v8 v8.32.4
|
||||
github.com/rqlite/rqlite/v8 v8.32.5
|
||||
github.com/stretchr/testify v1.9.0
|
||||
github.com/tidwall/gjson v1.18.0
|
||||
github.com/txix-open/etp/v3 v3.2.0
|
||||
github.com/txix-open/isp-kit v1.39.0
|
||||
github.com/txix-open/etp/v4 v4.0.1
|
||||
github.com/txix-open/isp-kit v1.39.1
|
||||
github.com/xeipuuv/gojsonschema v1.2.0
|
||||
golang.org/x/sync v0.8.0
|
||||
google.golang.org/grpc v1.67.1
|
||||
@@ -28,7 +28,7 @@ require (
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/coder/websocket v1.8.12 // indirect
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
|
||||
github.com/fatih/color v1.17.0 // indirect
|
||||
github.com/fatih/color v1.18.0 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.6 // indirect
|
||||
github.com/getsentry/sentry-go v0.29.1 // indirect
|
||||
github.com/go-logr/logr v1.4.2 // indirect
|
||||
@@ -62,7 +62,7 @@ require (
|
||||
github.com/prometheus/procfs v0.15.1 // indirect
|
||||
github.com/rqlite/go-sqlite3 v1.36.0 // indirect
|
||||
github.com/rqlite/raft-boltdb/v2 v2.0.0-20230523104317-c08e70f4de48 // indirect
|
||||
github.com/rqlite/sql v0.0.0-20240312185922-ffac88a740bd // indirect
|
||||
github.com/rqlite/sql v0.0.0-20241029220113-152a320b02f7 // indirect
|
||||
github.com/sethvargo/go-retry v0.3.0 // indirect
|
||||
github.com/tidwall/match v1.1.1 // indirect
|
||||
github.com/tidwall/pretty v1.2.1 // indirect
|
||||
|
||||
@@ -32,8 +32,8 @@ github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8Yc
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk=
|
||||
github.com/fatih/color v1.17.0 h1:GlRw1BRJxkpqUCBKzKOw098ed57fEsKeNjpTe3cSjK4=
|
||||
github.com/fatih/color v1.17.0/go.mod h1:YZ7TlrGPkiz6ku9fK3TLD/pl3CpsiFyu8N92HLgmosI=
|
||||
github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
|
||||
github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
|
||||
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
|
||||
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
|
||||
github.com/gabriel-vasile/mimetype v1.4.6 h1:3+PzJTKLkvgjeTbts6msPJt4DixhT4YtFNf1gtGe3zc=
|
||||
@@ -201,10 +201,10 @@ github.com/rqlite/gorqlite v0.0.0-20241013203532-4385768ae85d h1:c88ius/WcN19inn
|
||||
github.com/rqlite/gorqlite v0.0.0-20241013203532-4385768ae85d/go.mod h1:xF/KoXmrRyahPfo5L7Szb5cAAUl53dMWBh9cMruGEZg=
|
||||
github.com/rqlite/raft-boltdb/v2 v2.0.0-20230523104317-c08e70f4de48 h1:NZ62M+kT0JqhyFUMc8I4SMmfmD4NGJxhb2ePJQXjryc=
|
||||
github.com/rqlite/raft-boltdb/v2 v2.0.0-20230523104317-c08e70f4de48/go.mod h1:CRnsxgy5G8fAf5J+AM0yrsSdxXHKkIYOaq2sm+Q4DYc=
|
||||
github.com/rqlite/rqlite/v8 v8.32.4 h1:z3C4kDLGHVQ9qz7vbgDkrrEyXfJtAX+JoTy0u0+71DA=
|
||||
github.com/rqlite/rqlite/v8 v8.32.4/go.mod h1:cKc8BMsAiHwj7h+pkVf1WdND9viCFbktFudDIA6hWbs=
|
||||
github.com/rqlite/sql v0.0.0-20240312185922-ffac88a740bd h1:wW6BtayFoKaaDeIvXRE3SZVPOscSKlYD+X3bB749+zk=
|
||||
github.com/rqlite/sql v0.0.0-20240312185922-ffac88a740bd/go.mod h1:ib9zVtNgRKiGuoMyUqqL5aNpk+r+++YlyiVIkclVqPg=
|
||||
github.com/rqlite/rqlite/v8 v8.32.5 h1:wEzDX2HrGWMvFkg2fcCmi+rb1wQ1m5yEefUQfOMvMSY=
|
||||
github.com/rqlite/rqlite/v8 v8.32.5/go.mod h1:a1irqNWEZ+pWuWpgekbScCXp85QtNTJLarN3bVPjn9M=
|
||||
github.com/rqlite/sql v0.0.0-20241029220113-152a320b02f7 h1:Mnz6yd4FWtiD6bbH9WHFFHfrOM2OYTUTmwrsckRc4W8=
|
||||
github.com/rqlite/sql v0.0.0-20241029220113-152a320b02f7/go.mod h1:ib9zVtNgRKiGuoMyUqqL5aNpk+r+++YlyiVIkclVqPg=
|
||||
github.com/sethvargo/go-retry v0.3.0 h1:EEt31A35QhrcRZtrYFDTBg91cqZVnFL2navjDrah2SE=
|
||||
github.com/sethvargo/go-retry v0.3.0/go.mod h1:mNX17F0C/HguQMyMyJxcnU471gOZGxCLyYaFyAZraas=
|
||||
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
|
||||
@@ -233,12 +233,12 @@ github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhso
|
||||
github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM=
|
||||
github.com/txix-open/bellows v1.2.0 h1:CXv8nQaZtB/micraeRilYyj/gtfv+bqBgP5aPYQgjeY=
|
||||
github.com/txix-open/bellows v1.2.0/go.mod h1:qbKCy+RTgD30Qpw1fyb3y3jp5Y9mGhLLxgae1l0W92o=
|
||||
github.com/txix-open/etp/v3 v3.2.0 h1:EgTchT8VtCYV1iEo/y4jII3/NybrXiQDE0y6pmS350M=
|
||||
github.com/txix-open/etp/v3 v3.2.0/go.mod h1:lgen0TJmiturgBhvlxH1/PQ7iLL/OebKbxPAQYkuKI0=
|
||||
github.com/txix-open/etp/v4 v4.0.1 h1:5VSYgGsvnMz0tvUHsjVWFETI0qWBTCF1O3ARCHaCIgA=
|
||||
github.com/txix-open/etp/v4 v4.0.1/go.mod h1:FIu7TUDdwcgmtmF6tFTV1bGA2fRY/iVaPQdsGzvqYc8=
|
||||
github.com/txix-open/grmq v1.6.0 h1:V4QRb0sI2CMfdMaMsFGvGvUIDGad5vr3khNU7A3LlP8=
|
||||
github.com/txix-open/grmq v1.6.0/go.mod h1:s+NNNv42+32yLpjvl2tpqtyBbMB9e7kKFee3lfa/dyo=
|
||||
github.com/txix-open/isp-kit v1.39.0 h1:NBV2oJJefH/qt2pcPrqEmYccJedjPaVCwr6Z955C+pg=
|
||||
github.com/txix-open/isp-kit v1.39.0/go.mod h1:R4vwujGjMXLQir8MDDCfsDQa0CWGuZBSMakt5qcybgM=
|
||||
github.com/txix-open/isp-kit v1.39.1 h1:10zEILNQSPY7naiuaQkIKNS2/fnWxuE9bz+dTiAptXw=
|
||||
github.com/txix-open/isp-kit v1.39.1/go.mod h1:xB6mkoOewZBI1ND8kjU5TR6kvLu3VQI3Rdkh6g6FE4I=
|
||||
github.com/txix-open/jsonschema v1.2.0 h1:B8TrdSsPhDvYv67oi/LVqf7/+PuqFlMsNwUzGeHfl1s=
|
||||
github.com/txix-open/jsonschema v1.2.0/go.mod h1:l8YDZ1nvJrw6uxWowSVOxCV/ebiMJyapffW87ZEqH00=
|
||||
github.com/txix-open/validator/v10 v10.0.0-20240401163703-e83541b40f99 h1:Z0Sqf+U+Sc6hfIXtRCIZlbJprkCjwMFbS4ZbEPQ44To=
|
||||
|
||||
+3
-5
@@ -1,14 +1,12 @@
|
||||
package helpers
|
||||
|
||||
import (
|
||||
"net"
|
||||
"strconv"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/etp/v3"
|
||||
"github.com/txix-open/etp/v4"
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"isp-config-service/entity"
|
||||
"net"
|
||||
)
|
||||
|
||||
func ModuleName(conn *etp.Conn) string {
|
||||
@@ -29,6 +27,6 @@ func SplitAddress(backend entity.Backend) (cluster.AddressConfiguration, error)
|
||||
func LogFields(conn *etp.Conn) []log.Field {
|
||||
return []log.Field{
|
||||
log.String("moduleName", ModuleName(conn)),
|
||||
log.String("connId", strconv.FormatUint(conn.Id(), 10)),
|
||||
log.String("connId", conn.Id()),
|
||||
}
|
||||
}
|
||||
@@ -2,9 +2,9 @@ package middlewares
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/txix-open/etp/v4"
|
||||
|
||||
"github.com/txix-open/etp/v3"
|
||||
"github.com/txix-open/etp/v3/msg"
|
||||
"github.com/txix-open/etp/v4/msg"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"isp-config-service/helpers"
|
||||
)
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
-- +goose Up
|
||||
drop table isp_config_service__backend;
|
||||
|
||||
create table isp_config_service__backend
|
||||
(
|
||||
ws_connection_id text not null,
|
||||
module_id text not null,
|
||||
address text not null,
|
||||
version text not null,
|
||||
lib_version text not null,
|
||||
module_name text not null,
|
||||
config_service_node_id text not null,
|
||||
endpoints blob not null,
|
||||
required_modules blob not null,
|
||||
created_at integer not null default (unixepoch()),
|
||||
primary key (ws_connection_id),
|
||||
foreign key (module_id) references isp_config_service__module (id) on delete cascade on update cascade
|
||||
);
|
||||
|
||||
create index IX_isp_config_service__backend__module_id on isp_config_service__backend (module_id);
|
||||
create index IX_isp_config_service__backend__node_id on isp_config_service__backend(config_service_node_id);
|
||||
|
||||
-- +goose Down
|
||||
+56
-15
@@ -21,21 +21,17 @@ func NewBackend(db db.DB) Backend {
|
||||
}
|
||||
}
|
||||
|
||||
func (r Backend) Upsert(ctx context.Context, backend entity.Backend) error {
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Backend.Upsert")
|
||||
func (r Backend) Insert(ctx context.Context, backend entity.Backend) error {
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Backend.Insert")
|
||||
|
||||
query, args, err := squirrel.Insert(Table("backend")).
|
||||
Columns("module_id", "address",
|
||||
"version", "lib_version", "module_name",
|
||||
Columns("ws_connection_id", "module_id", "address",
|
||||
"version", "lib_version", "module_name", "config_service_node_id",
|
||||
"endpoints", "required_modules").
|
||||
Values(backend.ModuleId, backend.Address,
|
||||
backend.Version, backend.LibVersion, backend.ModuleName,
|
||||
Values(backend.WsConnectionId, backend.ModuleId, backend.Address,
|
||||
backend.Version, backend.LibVersion, backend.ModuleName, backend.ConfigServiceNodeId,
|
||||
backend.Endpoints, backend.RequiredModules,
|
||||
).Suffix(`on conflict (module_id, address) do update
|
||||
set version = excluded.version, lib_version = excluded.lib_version, module_name = excluded.module_name,
|
||||
endpoints = excluded.endpoints, required_modules = excluded.required_modules,
|
||||
updated_at = unixepoch()
|
||||
`).
|
||||
).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "build query")
|
||||
@@ -49,13 +45,12 @@ func (r Backend) Upsert(ctx context.Context, backend entity.Backend) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r Backend) Delete(ctx context.Context, moduleId string, address string) error {
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Backend.Delete")
|
||||
func (r Backend) DeleteByWsConnectionIds(ctx context.Context, wsConnectionIds []string) error {
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Backend.DeleteByWsConnectionIds")
|
||||
|
||||
query, args, err := squirrel.Delete(Table("backend")).
|
||||
Where(squirrel.Eq{
|
||||
"module_id": moduleId,
|
||||
"address": address,
|
||||
"ws_connection_id": wsConnectionIds,
|
||||
}).ToSql()
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "build query")
|
||||
@@ -69,6 +64,52 @@ func (r Backend) Delete(ctx context.Context, moduleId string, address string) er
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r Backend) DeleteByConfigServiceNodeId(ctx context.Context, configServiceNodeId string) (int, error) {
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Backend.DeleteByConfigServiceNodeId")
|
||||
|
||||
query, args, err := squirrel.Delete(Table("backend")).
|
||||
Where(squirrel.Eq{
|
||||
"config_service_node_id": configServiceNodeId,
|
||||
}).ToSql()
|
||||
if err != nil {
|
||||
return 0, errors.WithMessage(err, "build query")
|
||||
}
|
||||
|
||||
result, err := r.db.Exec(ctx, query, args...)
|
||||
if err != nil {
|
||||
return 0, errors.WithMessagef(err, "exec: %s", query)
|
||||
}
|
||||
|
||||
deleted, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return 0, errors.WithMessage(err, "rows affected")
|
||||
}
|
||||
|
||||
return int(deleted), nil
|
||||
}
|
||||
|
||||
func (r Backend) GetByConfigServiceNodeId(ctx context.Context, configServiceNodeId string) ([]entity.Backend, error) {
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Backend.GetByConfigServiceNodeId")
|
||||
|
||||
query, args, err := squirrel.Select("*").
|
||||
From(Table("backend")).
|
||||
Where(squirrel.Eq{
|
||||
"config_service_node_id": configServiceNodeId,
|
||||
}).OrderBy("created_at desc").
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "build query")
|
||||
}
|
||||
|
||||
result := make([]entity.Backend, 0)
|
||||
err = r.db.Select(ctx, &result, query, args...)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessagef(err, "select: %s", query)
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (r Backend) All(ctx context.Context) ([]entity.Backend, error) {
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Backend.All")
|
||||
|
||||
|
||||
+1
-1
@@ -1,10 +1,10 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"github.com/txix-open/etp/v4"
|
||||
"isp-config-service/conf"
|
||||
"net/http"
|
||||
|
||||
"github.com/txix-open/etp/v3"
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/endpoint"
|
||||
|
||||
@@ -158,7 +158,7 @@ func (s Module) backendToDto(backend entity.Backend) (domain.Connection, error)
|
||||
Port: addr.Port,
|
||||
},
|
||||
Endpoints: endpointsDescriptors,
|
||||
EstablishedAt: time.Time(backend.UpdatedAt),
|
||||
EstablishedAt: time.Time(backend.CreatedAt),
|
||||
}
|
||||
|
||||
return conn, nil
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
package backend
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/etp/v4"
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"isp-config-service/entity"
|
||||
"isp-config-service/entity/xtypes"
|
||||
)
|
||||
|
||||
type Repo interface {
|
||||
Insert(ctx context.Context, backend entity.Backend) error
|
||||
DeleteByWsConnectionIds(ctx context.Context, wsConnIds []string) error
|
||||
GetByConfigServiceNodeId(ctx context.Context, configServiceNodeId string) ([]entity.Backend, error)
|
||||
DeleteByConfigServiceNodeId(ctx context.Context, configServiceNodeId string) (int, error)
|
||||
}
|
||||
|
||||
type EventRepo interface {
|
||||
Insert(ctx context.Context, event entity.Event) error
|
||||
}
|
||||
|
||||
type Backend struct {
|
||||
backendRepo Repo
|
||||
eventRepo EventRepo
|
||||
nodeId string
|
||||
rooms *etp.Rooms
|
||||
logger log.Logger
|
||||
}
|
||||
|
||||
func NewBackend(
|
||||
backendRepo Repo,
|
||||
eventRepo EventRepo,
|
||||
nodeId string,
|
||||
rooms *etp.Rooms,
|
||||
logger log.Logger,
|
||||
) Backend {
|
||||
return Backend{
|
||||
backendRepo: backendRepo,
|
||||
eventRepo: eventRepo,
|
||||
nodeId: nodeId,
|
||||
rooms: rooms,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (s Backend) Connect(
|
||||
ctx context.Context,
|
||||
connId string,
|
||||
moduleId string,
|
||||
declaration cluster.BackendDeclaration,
|
||||
) (*entity.Backend, error) {
|
||||
backend := entity.Backend{
|
||||
WsConnectionId: connId,
|
||||
ModuleId: moduleId,
|
||||
Address: fmt.Sprintf("%s:%s", declaration.Address.IP, declaration.Address.Port),
|
||||
Version: declaration.Version,
|
||||
LibVersion: declaration.LibVersion,
|
||||
ModuleName: declaration.ModuleName,
|
||||
ConfigServiceNodeId: s.nodeId,
|
||||
Endpoints: xtypes.Json[[]cluster.EndpointDescriptor]{Value: declaration.Endpoints},
|
||||
RequiredModules: xtypes.Json[[]cluster.ModuleDependency]{Value: declaration.RequiredModules},
|
||||
CreatedAt: xtypes.Time{},
|
||||
}
|
||||
err := s.backendRepo.Insert(ctx, backend)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "upsert backend in store")
|
||||
}
|
||||
|
||||
event := entity.NewEvent(entity.EventPayload{
|
||||
ModuleReady: &entity.PayloadModuleReady{
|
||||
ModuleId: moduleId,
|
||||
},
|
||||
})
|
||||
err = s.eventRepo.Insert(ctx, event)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "insert event in store")
|
||||
}
|
||||
|
||||
return &backend, nil
|
||||
}
|
||||
|
||||
func (s Backend) Disconnect(ctx context.Context, backend entity.Backend) error {
|
||||
err := s.backendRepo.DeleteByWsConnectionIds(ctx, []string{backend.WsConnectionId})
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "delete backend in store")
|
||||
}
|
||||
|
||||
err = s.insertDisconnectEvent(ctx, backend.ModuleId)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "insert disconnect event")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Backend) ClearPhantomBackends(ctx context.Context) (int, error) {
|
||||
backends, err := s.backendRepo.GetByConfigServiceNodeId(ctx, s.nodeId)
|
||||
if err != nil {
|
||||
return 0, errors.WithMessagef(err, "get by config service node id = '%s'", s.nodeId)
|
||||
}
|
||||
|
||||
toDelete := make([]string, 0)
|
||||
modulesToDisconnect := make(map[string]bool)
|
||||
for _, backend := range backends {
|
||||
_, ok := s.rooms.Get(backend.WsConnectionId)
|
||||
if ok {
|
||||
continue
|
||||
}
|
||||
|
||||
toDelete = append(toDelete, backend.WsConnectionId)
|
||||
modulesToDisconnect[backend.ModuleId] = true
|
||||
}
|
||||
|
||||
if len(toDelete) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
err = s.backendRepo.DeleteByWsConnectionIds(ctx, toDelete)
|
||||
if err != nil {
|
||||
return 0, errors.WithMessage(err, "delete backends by ws connection ids")
|
||||
}
|
||||
|
||||
for moduleId := range modulesToDisconnect {
|
||||
err := s.insertDisconnectEvent(ctx, moduleId)
|
||||
if err != nil {
|
||||
return 0, errors.WithMessage(err, "insert disconnect event")
|
||||
}
|
||||
}
|
||||
|
||||
return len(toDelete), nil
|
||||
}
|
||||
|
||||
func (s Backend) DeleteOwnBackends(ctx context.Context) {
|
||||
deleted, err := s.backendRepo.DeleteByConfigServiceNodeId(ctx, s.nodeId)
|
||||
if err != nil {
|
||||
s.logger.Error(ctx, errors.WithMessagef(err, "delete by config service node id = '%s'", s.nodeId))
|
||||
return
|
||||
}
|
||||
s.logger.Info(ctx, fmt.Sprintf("delete %d own backends", deleted))
|
||||
}
|
||||
|
||||
func (s Backend) insertDisconnectEvent(ctx context.Context, moduleId string) error {
|
||||
event := entity.NewEvent(entity.EventPayload{
|
||||
ModuleDisconnected: &entity.PayloadModuleDisconnected{
|
||||
ModuleId: moduleId,
|
||||
},
|
||||
})
|
||||
err := s.eventRepo.Insert(ctx, event)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "insert event in store")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package backend
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
type Service interface {
|
||||
ClearPhantomBackends(ctx context.Context) (int, error)
|
||||
}
|
||||
|
||||
type Cleaner struct {
|
||||
service Service
|
||||
logger log.Logger
|
||||
}
|
||||
|
||||
func NewCleaner(
|
||||
service Service,
|
||||
logger log.Logger,
|
||||
) Cleaner {
|
||||
return Cleaner{
|
||||
service: service,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (c Cleaner) Do(ctx context.Context) {
|
||||
ctx = log.ToContext(ctx, log.String("worker", "phantomBackendCleaner"))
|
||||
|
||||
deleted, err := c.service.ClearPhantomBackends(ctx)
|
||||
if err != nil {
|
||||
c.logger.Error(ctx, errors.WithMessage(err, "clear phantom backends"))
|
||||
return
|
||||
}
|
||||
|
||||
c.logger.Debug(ctx, fmt.Sprintf("delete %d phantom backends", deleted))
|
||||
}
|
||||
@@ -2,11 +2,11 @@ package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/txix-open/etp/v4"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/etp/v3"
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"isp-config-service/helpers"
|
||||
@@ -51,7 +51,7 @@ func (s Emitter) Emit(
|
||||
if err != nil {
|
||||
err := errors.WithMessagef(
|
||||
err,
|
||||
"emit event '%s', to %s module, connId: %d",
|
||||
"emit event '%s', to %s module, connId: %s",
|
||||
event, helpers.ModuleName(conn), conn.Id(),
|
||||
)
|
||||
s.logger.Error(ctx, err)
|
||||
|
||||
+13
-51
@@ -4,12 +4,10 @@ import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/etp/v3"
|
||||
"github.com/txix-open/etp/v3/store"
|
||||
"github.com/txix-open/etp/v4"
|
||||
"github.com/txix-open/etp/v4/store"
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"isp-config-service/entity"
|
||||
@@ -30,13 +28,9 @@ type Repo interface {
|
||||
) error
|
||||
}
|
||||
|
||||
type BackendRepo interface {
|
||||
Upsert(ctx context.Context, backend entity.Backend) error
|
||||
Delete(ctx context.Context, moduleId string, address string) error
|
||||
}
|
||||
|
||||
type EventRepo interface {
|
||||
Insert(ctx context.Context, event entity.Event) error
|
||||
type BackendService interface {
|
||||
Connect(ctx context.Context, connId string, moduleId string, declaration cluster.BackendDeclaration) (*entity.Backend, error)
|
||||
Disconnect(ctx context.Context, backend entity.Backend) error
|
||||
}
|
||||
|
||||
type ConfigSchemaRepo interface {
|
||||
@@ -56,8 +50,7 @@ type SubscriptionService interface {
|
||||
|
||||
type Service struct {
|
||||
moduleRepo Repo
|
||||
backendRepo BackendRepo
|
||||
eventRepo EventRepo
|
||||
backendService BackendService
|
||||
configRepo ConfigRepo
|
||||
configSchemaRepo ConfigSchemaRepo
|
||||
subscriptionService SubscriptionService
|
||||
@@ -67,8 +60,7 @@ type Service struct {
|
||||
|
||||
func NewService(
|
||||
moduleRepo Repo,
|
||||
backendRepo BackendRepo,
|
||||
eventRepo EventRepo,
|
||||
backendService BackendService,
|
||||
configRepo ConfigRepo,
|
||||
configSchemaRepo ConfigSchemaRepo,
|
||||
subscriptionService SubscriptionService,
|
||||
@@ -77,8 +69,7 @@ func NewService(
|
||||
) Service {
|
||||
return Service{
|
||||
moduleRepo: moduleRepo,
|
||||
backendRepo: backendRepo,
|
||||
eventRepo: eventRepo,
|
||||
backendService: backendService,
|
||||
configRepo: configRepo,
|
||||
configSchemaRepo: configSchemaRepo,
|
||||
subscriptionService: subscriptionService,
|
||||
@@ -136,19 +127,9 @@ func (s Service) OnDisconnect(
|
||||
|
||||
backend, _ := store.Get[entity.Backend](conn.Data(), backendKey)
|
||||
if backend.ModuleId != "" {
|
||||
err = s.backendRepo.Delete(ctx, backend.ModuleId, backend.Address)
|
||||
err := s.backendService.Disconnect(ctx, backend)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "delete backend in store")
|
||||
}
|
||||
|
||||
event := entity.NewEvent(entity.EventPayload{
|
||||
ModuleDisconnected: &entity.PayloadModuleDisconnected{
|
||||
ModuleId: moduleId,
|
||||
},
|
||||
})
|
||||
err = s.eventRepo.Insert(ctx, event)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "insert event in store")
|
||||
return errors.WithMessage(err, "disconnect")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -173,31 +154,12 @@ func (s Service) OnModuleReady(
|
||||
return errors.WithMessage(err, "resolve module id")
|
||||
}
|
||||
|
||||
backend := entity.Backend{
|
||||
ModuleId: moduleId,
|
||||
Address: fmt.Sprintf("%s:%s", declaration.Address.IP, declaration.Address.Port),
|
||||
Version: declaration.Version,
|
||||
LibVersion: declaration.LibVersion,
|
||||
ModuleName: declaration.ModuleName,
|
||||
Endpoints: xtypes.Json[[]cluster.EndpointDescriptor]{Value: declaration.Endpoints},
|
||||
RequiredModules: xtypes.Json[[]cluster.ModuleDependency]{Value: declaration.RequiredModules},
|
||||
}
|
||||
err = s.backendRepo.Upsert(ctx, backend)
|
||||
backend, err := s.backendService.Connect(ctx, conn.Id(), moduleId, declaration)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "upsert backend in store")
|
||||
return errors.WithMessage(err, "connect")
|
||||
}
|
||||
|
||||
conn.Data().Set(backendKey, backend)
|
||||
|
||||
event := entity.NewEvent(entity.EventPayload{
|
||||
ModuleReady: &entity.PayloadModuleReady{
|
||||
ModuleId: moduleId,
|
||||
},
|
||||
})
|
||||
err = s.eventRepo.Insert(ctx, event)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "insert event in store")
|
||||
}
|
||||
conn.Data().Set(backendKey, *backend)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
+18
-25
@@ -7,7 +7,6 @@ import (
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/pressly/goose/v3"
|
||||
"github.com/txix-open/etp/v3"
|
||||
"github.com/txix-open/isp-kit/app"
|
||||
"github.com/txix-open/isp-kit/bootstrap"
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
@@ -18,7 +17,6 @@ import (
|
||||
"github.com/txix-open/isp-kit/http/httpclix"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/observability/sentry"
|
||||
"github.com/txix-open/isp-kit/worker"
|
||||
"isp-config-service/assembly"
|
||||
"isp-config-service/conf"
|
||||
"isp-config-service/middlewares"
|
||||
@@ -41,9 +39,7 @@ type Service struct {
|
||||
logger log.Logger
|
||||
|
||||
// initialized in Run
|
||||
etpSrv *etp.Server
|
||||
handleEventWorker *worker.Worker
|
||||
cleanEventWorker *worker.Worker
|
||||
locatorConfig *assembly.Config
|
||||
}
|
||||
|
||||
func New(boot *bootstrap.Bootstrap) (*Service, error) {
|
||||
@@ -121,15 +117,13 @@ func (s *Service) Run(ctx context.Context) error {
|
||||
Local: s.cfg,
|
||||
RqliteAddress: s.rqlite.LocalHttpAddr(),
|
||||
}
|
||||
config := assembly.NewLocator(db, s.rqlite, cfg, s.logger).Config()
|
||||
s.etpSrv = config.EtpSrv
|
||||
s.handleEventWorker = config.HandleEventWorker
|
||||
s.cleanEventWorker = config.CleanEventWorker
|
||||
s.grpcSrv.Upgrade(config.GrpcMux)
|
||||
s.httpSrv.Upgrade(config.HttpMux)
|
||||
s.locatorConfig = assembly.NewLocator(db, s.rqlite, cfg, s.logger).Config()
|
||||
s.grpcSrv.Upgrade(s.locatorConfig.GrpcMux)
|
||||
s.httpSrv.Upgrade(s.locatorConfig.HttpMux)
|
||||
|
||||
s.handleEventWorker.Run(ctx)
|
||||
s.cleanEventWorker.Run(ctx)
|
||||
s.locatorConfig.HandleEventWorker.Run(ctx)
|
||||
s.locatorConfig.CleanEventWorker.Run(ctx)
|
||||
s.locatorConfig.CleanPhantomBackendWorker.Run(ctx)
|
||||
|
||||
go func() {
|
||||
s.logger.Debug(ctx, fmt.Sprintf("starting grpc server on %s", s.boot.BindingAddress))
|
||||
@@ -174,20 +168,19 @@ func (s *Service) Closers() []app.Closer {
|
||||
return s.httpSrv.Shutdown(ctx)
|
||||
}),
|
||||
app.CloserFunc(func() error {
|
||||
if s.handleEventWorker != nil {
|
||||
s.handleEventWorker.Shutdown()
|
||||
}
|
||||
if s.cleanEventWorker != nil {
|
||||
s.cleanEventWorker.Shutdown()
|
||||
}
|
||||
return nil
|
||||
}),
|
||||
app.CloserFunc(func() error {
|
||||
if s.etpSrv == nil {
|
||||
if s.locatorConfig == nil {
|
||||
return nil
|
||||
}
|
||||
s.etpSrv.OnDisconnect(nil)
|
||||
s.etpSrv.Shutdown()
|
||||
|
||||
s.locatorConfig.HandleEventWorker.Shutdown()
|
||||
s.locatorConfig.CleanEventWorker.Shutdown()
|
||||
s.locatorConfig.CleanPhantomBackendWorker.Shutdown()
|
||||
|
||||
s.locatorConfig.EtpSrv.OnDisconnect(nil)
|
||||
s.locatorConfig.EtpSrv.Shutdown()
|
||||
|
||||
s.locatorConfig.OwnBackendsCleaner.DeleteOwnBackends(context.Background())
|
||||
|
||||
return nil
|
||||
}),
|
||||
s.rqlite,
|
||||
|
||||
@@ -2,9 +2,9 @@ package subscription
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/txix-open/etp/v4"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/etp/v3"
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
|
||||
Reference in new issue
Block a user