Compare commits

..
16 Commits
Author SHA1 Message Date
ykomissarov 050c7bc51f add migrations 2019-11-07 17:02:45 +03:00
ykomissarov 775edf889c add migrations 2019-11-07 17:02:22 +03:00
ykomissarov c0e69cec76 fix doc 2019-09-09 14:13:32 +03:00
ykomissarov 644c3f278e fix doc 2019-09-09 14:08:23 +03:00
DeniskaRediska 03e84301cc fix(doc generate) 2019-09-05 18:37:21 +03:00
ykomissarov ce953e3799 add doc 2019-08-28 13:35:48 +03:00
DeniskaRediska 677fe21eb8 fix(build with updated libs) 2019-07-26 11:44:37 +03:00
DeniskaRediska 0276feb0e7 add(not found for schema request) 2019-07-26 11:33:18 +03:00
DeniskaRediska 4d6a7a4c0b refactoring 2019-07-26 11:24:55 +03:00
DeniskaRediska c8dfcc61fc add(method for get schema by module_id) 2019-07-25 18:58:46 +03:00
ykomissarov baa80464a4 fix module init 2019-06-06 17:22:12 +03:00
ykomissarov 677432de7b fix module init 2019-06-06 17:22:04 +03:00
ykomissarov 7b4d8ff7ef fix migration 2019-05-15 13:00:47 +03:00
ykomissarov a8e430e97a fix migration 2019-05-15 12:52:23 +03:00
ykomissarov 2cbf355f5f Merge branch 'v2' 2019-05-13 16:53:52 +03:00
ykomissarov 77b18a0382 change default configs for auth and admin 2019-05-08 16:43:53 +03:00
124 changed files with 4790 additions and 5826 deletions

No files matched your search

+1 -1
View File
@@ -1 +1 @@
2.0.3
1.2.2
+6 -15
View File
@@ -1,18 +1,9 @@
### v2.0.3
* fix data race when applyCommandOnLeader in websocket handler
* update dependencies
### v2.0.2
* fix raft server address announcing (serverId == serverAddress == cluster.outerAddress)
### v2.0.1
* fix nil pointer dereference in repositories
* increase default websocket ConnectionReadLimit to 4 MB, add to configuration
### v2.0.0
* full rewrite to support cluster mode
* change websocket protocol from socketio to etp
### v1.2.2
* add migrations temp
### v1.2.1
* fix doc generate
### v1.2.0
* add method `GetSchemaByModuleId`
### v1.1.0
* update libs
* default config handling
Generated
+161 -307
View File
@@ -2,23 +2,12 @@
[[projects]]
digest = "1:d5e752c67b445baa5b6cb6f8aa706775c2aa8e41aca95a0c651520ff2c80361a"
name = "github.com/Microsoft/go-winio"
packages = [
".",
"pkg/guid",
]
pruneopts = "UT"
revision = "6c72808b55902eae4c5943626030429ff20f3b63"
version = "v0.4.14"
[[projects]]
branch = "master"
digest = "1:7a9140c806333a78122763d08ec6c0d7358c7fff1df8cfbb01881c5dc46e24e5"
name = "github.com/armon/go-metrics"
digest = "1:e92f5581902c345eb4ceffdcd4a854fb8f73cf436d47d837d1ec98ef1fe0a214"
name = "github.com/StackExchange/wmi"
packages = ["."]
pruneopts = "UT"
revision = "ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5"
revision = "5d049714c4a64225c3c79a7cf7d02f7fb5b96338"
version = "1.0.0"
[[projects]]
digest = "1:320e7ead93de9fd2b0e59b50fd92a4d50c1f8ab455d96bc2eb083267453a9709"
@@ -28,14 +17,6 @@
revision = "ccb8e960c48f04d6935e72476ae4a51028f9e22f"
version = "v9"
[[projects]]
digest = "1:0f98f59e9a2f4070d66f0c9c39561f68fcd1dc837b22a852d28d0003aebd1b1e"
name = "github.com/boltdb/bolt"
packages = ["."]
pruneopts = "UT"
revision = "2f1ce7a837dcb8da3ec595b1dac9d0632f0f99e8"
version = "v1.3.1"
[[projects]]
digest = "1:652880afc6b57ce0a67173f552cb35ccda816493a1da6ca20e5074a66bcd083f"
name = "github.com/buaazp/fasthttprouter"
@@ -52,70 +33,6 @@
revision = "4b4cebaf850ec58f1bb1fec5bdebdf8501c2bc3f"
version = "v3.0.0"
[[projects]]
digest = "1:ffe9824d294da03b391f44e1ae8281281b4afc1bdaa9588c9097785e3af10cec"
name = "github.com/davecgh/go-spew"
packages = ["spew"]
pruneopts = "UT"
revision = "8991bc29aa16c548c550c7ff78260e27b9ab7c73"
version = "v1.1.1"
[[projects]]
digest = "1:4ddc17aeaa82cb18c5f0a25d7c253a10682f518f4b2558a82869506eec223d76"
name = "github.com/docker/distribution"
packages = [
"digestset",
"reference",
]
pruneopts = "UT"
revision = "2461543d988979529609e8cb6fca9ca190dc48da"
version = "v2.7.1"
[[projects]]
digest = "1:c4c7064c2c67a0a00815918bae489dd62cd88d859d24c95115d69b00b3d33334"
name = "github.com/docker/docker"
packages = [
"api/types",
"api/types/blkiodev",
"api/types/container",
"api/types/events",
"api/types/filters",
"api/types/mount",
"api/types/network",
"api/types/reference",
"api/types/registry",
"api/types/strslice",
"api/types/swarm",
"api/types/time",
"api/types/versions",
"api/types/volume",
"client",
"pkg/tlsconfig",
]
pruneopts = "UT"
revision = "092cba3727bb9b4a2f0e922cd6c0f93ea270e363"
version = "v1.13.1"
[[projects]]
digest = "1:811c86996b1ca46729bad2724d4499014c4b9effd05ef8c71b852aad90deb0ce"
name = "github.com/docker/go-connections"
packages = [
"nat",
"sockets",
"tlsconfig",
]
pruneopts = "UT"
revision = "7395e3f8aa162843a74ed6d48e79627d9792ac55"
version = "v0.4.0"
[[projects]]
digest = "1:e95ef557dc3120984bb66b385ae01b4bb8ff56bcde28e7b0d1beed0cccc4d69f"
name = "github.com/docker/go-units"
packages = ["."]
pruneopts = "UT"
revision = "519db1ee28dcc9fd2474ae59fca29a810482bfb1"
version = "v0.4.0"
[[projects]]
digest = "1:abeb38ade3f32a92943e5be54f55ed6d6e3b6602761d74b4aab4c9dd45c18abd"
name = "github.com/fsnotify/fsnotify"
@@ -124,6 +41,17 @@
revision = "c2828203cd70a50dcccfb2761f8b1f8ceef9a8e9"
version = "v1.4.7"
[[projects]]
digest = "1:440028f55cb322d8cb5b9d5ebec298a00b7d74690a658fe6b1c0c0b44341bfae"
name = "github.com/go-ole/go-ole"
packages = [
".",
"oleutil",
]
pruneopts = "UT"
revision = "97b6244175ae18ea6eef668034fd6565847501c9"
version = "v1.2.4"
[[projects]]
digest = "1:f9448bfab8ebe44e3d91e4e4475cf92d60789a614652f361df4e41972c9d5caf"
name = "github.com/go-pg/pg"
@@ -143,67 +71,66 @@
version = "v8.0.6"
[[projects]]
digest = "1:07f4fafe81587b642166199f41c3edcca12929fcfcc0261b00be5dea2f968f44"
digest = "1:b532ee3f683c057e797694b5bfeb3827d89e6adf41c53dbc80e549bca76364ea"
name = "github.com/golang/protobuf"
packages = [
"jsonpb",
"proto",
"protoc-gen-go/descriptor",
"protoc-gen-go/generator",
"protoc-gen-go/generator/internal/remap",
"protoc-gen-go/plugin",
"ptypes",
"ptypes/any",
"ptypes/duration",
"ptypes/struct",
"ptypes/timestamp",
"ptypes/wrappers",
]
pruneopts = "UT"
revision = "6c65a5562fc06764971b7c5d05c76c75e84bdbf7"
version = "v1.3.2"
[[projects]]
digest = "1:0ade334594e69404d80d9d323445d2297ff8161637f9b2d347cc6973d2d6f05b"
name = "github.com/hashicorp/errwrap"
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 = "8a6fb523712970c966eefc6b39ed2c5e74880354"
version = "v1.0.0"
revision = "c8aeb1ed9b49d7de8fef8662efb18f1d289c5f2e"
[[projects]]
digest = "1:cf6b61e1b4c26b0c7526cee4a0cee6d8302b17798af4b2a56a90eedac0aef11a"
name = "github.com/hashicorp/go-hclog"
digest = "1:e62657cca9badaa308d86e7716083e4c5933bb78e30a17743fc67f50be26f6f4"
name = "github.com/gorilla/websocket"
packages = ["."]
pruneopts = "UT"
revision = "5ccdce08c75b6c7b37af61159f13f6a4f5e2e928"
version = "v0.9.2"
revision = "c3e18be99d19e6b3e8f1559eea2c161a665c4b6b"
version = "v1.4.1"
[[projects]]
digest = "1:6e9806a06d00f4d1f90806d7b5cfb11e35dca76503390ca6e704b05ea7051bff"
name = "github.com/hashicorp/go-immutable-radix"
packages = ["."]
digest = "1:99a9eab89cf8193a246811614678f34432e95446c34142594c450acb1a7a31cc"
name = "github.com/grpc-ecosystem/grpc-gateway"
packages = [
"internal",
"runtime",
"utilities",
]
pruneopts = "UT"
revision = "7dd1121b595e4e1bd6dd5caa78e0f5c454740379"
version = "v1.1.0"
[[projects]]
digest = "1:5d8539af558ca2ea960a4c11afb12c75ae9e9dca3560f1103318aaa2030e37e2"
name = "github.com/hashicorp/go-msgpack"
packages = ["codec"]
pruneopts = "UT"
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"
packages = ["simplelru"]
pruneopts = "UT"
revision = "7f827b33c0f158ec5dfbba01bb0b14a4541fd81d"
version = "v0.5.3"
revision = "471f45a5a99a578de7a8638dc7ed29e245bde097"
version = "v1.11.1"
[[projects]]
digest = "1:c0d19ab64b32ce9fe5cf4ddceba78d5bc9807f0016db6b1183599da3dcc24d10"
@@ -224,22 +151,6 @@
revision = "8cb6e5b959231cc1119e43259c4a608f9c51a241"
version = "v1.0.0"
[[projects]]
branch = "master"
digest = "1:f932a7af1d85151d9a33c8a8917390ddf155e531f4d48e3257604507445dc4e1"
name = "github.com/hashicorp/raft"
packages = ["."]
pruneopts = "UT"
revision = "a989b09b3c0112332ac6110625f0f06538ca0083"
[[projects]]
branch = "master"
digest = "1:8bc6831553a265c699a973640ea48eee53d3878af9013208d20a0c8807fa66ec"
name = "github.com/hashicorp/raft-boltdb"
packages = ["."]
pruneopts = "UT"
revision = "4207f1bf061751378aee6cdfe697965a13ab49d7"
[[projects]]
branch = "master"
digest = "1:2cf4ff28b309c93a52b3329c7a22d5375b137249d4ed63c9d40707a1b253f7df"
@@ -262,63 +173,37 @@
revision = "ac5582987a2f25e8743e0ebb7259312adda05c23"
[[projects]]
digest = "1:af0185228b5f1c08939721c26a61787c65d6d4cdd6ce5078d0bb86cb1d7a907a"
name = "github.com/integration-system/isp-etp-go"
branch = "master"
digest = "1:9e2fd899fdb17e28e9d036fe7a604a1e04918aa4865d5a2150008fc12c6134be"
name = "github.com/integration-system/golang-socketio"
packages = [
".",
"ack",
"bpool",
"client",
"gen",
"parser",
"protocol",
"transport",
]
pruneopts = "UT"
revision = "aab01a1b29ac06ebeb0216b9b43708491b8d5aee"
version = "v2.0.2"
revision = "5959fcea049facd9441fff9de976191accd3cf9f"
[[projects]]
digest = "1:d30832edf4ae7a45e863e216c89bb5f1d66c10ff5b3255b9e007598a048594d7"
digest = "1:c2cbe4bc2b4615c904b02e66538790b4b27e6637f9f414f35904c78b855fcf2d"
name = "github.com/integration-system/isp-lib"
packages = [
"atomic",
"backend",
"bootstrap",
"config",
"config/schema",
"database",
"logger",
"metric",
"proto/stubs",
"socket",
"streaming",
"structure",
"utils",
]
pruneopts = "UT"
revision = "abfa9a9776d64e6d04d495bfe00db8ca4dcbe7fc"
version = "v2.0.1"
[[projects]]
digest = "1:1562269205ab0c6685c8b0b99511e91b9d3627e4cac3f0288378bc8930e658f1"
name = "github.com/integration-system/isp-lib-test"
packages = [
"ctx",
"docker",
"utils",
"utils/postgres",
]
pruneopts = "UT"
revision = "6da4f1fed4b0df648a9b1c4bd4098fdd405695e1"
version = "v1.4.1"
[[projects]]
branch = "master"
digest = "1:1789fb6e57949a6e4cacb74023cd30efb04b09dc6111d6ef3718241ebb23ebe9"
name = "github.com/integration-system/isp-log"
packages = [
".",
"stdcodes",
]
pruneopts = "UT"
revision = "a22bf2e0b56a9ef47db4a98756e39f700a99b688"
revision = "ec379c1305f381a22a2934d406f4e3c3e20ef0c2"
version = "v1.6.2"
[[projects]]
branch = "master"
@@ -337,18 +222,18 @@
version = "v1.0.0"
[[projects]]
digest = "1:d78015a9da26d37166a2119592019e8bfe9b24bec60aff4a46db6110070fb1b2"
digest = "1:ac7f1061abc812a5d0de6df7e3f477cef942aef503848f436da0f0eb2603bfbf"
name = "github.com/json-iterator/go"
packages = [
".",
"extra",
]
pruneopts = "UT"
revision = "03217c3e97663914aec3faafde50d081f197a0a2"
version = "1.1.8"
revision = "27518f6661eba504be5a7a9a9f6d9460d892ade3"
version = "v1.1.7"
[[projects]]
digest = "1:acfc228fb5fbfb82645c121e3224bd546ed68aef6dfc87f63e2d8de099a3822b"
digest = "1:caa1da085cc12cd39d3ddb267434902f621050e1b46f7e9477b2b933df680193"
name = "github.com/klauspost/compress"
packages = [
"flate",
@@ -356,8 +241,16 @@
"zlib",
]
pruneopts = "UT"
revision = "a41f1a10bd3b167958ff6df80b800fe2969dd3ca"
version = "v1.9.0"
revision = "fdc46f09595ea8241b9bfe291bbc868a7af19e10"
version = "v1.8.2"
[[projects]]
digest = "1:923c4d7194b42e054b2eb8a6c62824ac55e23ececc1c7e48d4da69c971c55954"
name = "github.com/klauspost/cpuid"
packages = ["."]
pruneopts = "UT"
revision = "05a8198c0f5a27739aec358908d7e12c64ce6eb7"
version = "v1.2.1"
[[projects]]
digest = "1:31e761d97c76151dde79e9d28964a812c46efc5baee4085b86f68f0c654450de"
@@ -387,6 +280,30 @@
revision = "de8848e004dd33dc07a2947b3d76f618a7fc7ef1"
version = "v1.8.1"
[[projects]]
digest = "1:7c084e0e780596dd2a7e20d25803909a9a43689c153de953520dfbc0b0e51166"
name = "github.com/mattn/go-colorable"
packages = ["."]
pruneopts = "UT"
revision = "8029fb3788e5a4a9c00e415f586a6d033f5d38b3"
version = "v0.1.2"
[[projects]]
digest = "1:36325ebb862e0382f2f14feef409ba9351271b89ada286ae56836c603d43b59c"
name = "github.com/mattn/go-isatty"
packages = ["."]
pruneopts = "UT"
revision = "e1f7b56ace729e4a73a29a6b4fac6cd5fcda7ab3"
version = "v0.0.9"
[[projects]]
branch = "master"
digest = "1:2b32af4d2a529083275afc192d1067d8126b578c7a9613b26600e4df9c735155"
name = "github.com/mgutz/ansi"
packages = ["."]
pruneopts = "UT"
revision = "9520e82c474b0a04dd04f8a40959027271bab992"
[[projects]]
digest = "1:53bc4cd4914cd7cd52139990d5170d6dc99067ae31c56530621b18b35fc30318"
name = "github.com/mitchellh/mapstructure"
@@ -420,20 +337,12 @@
revision = "c48cc78d482608239f6c4c92a4abd87eb8761c90"
[[projects]]
digest = "1:ee4d4af67d93cc7644157882329023ce9a7bcfce956a079069a9405521c7cc8d"
name = "github.com/opencontainers/go-digest"
packages = ["."]
pruneopts = "UT"
revision = "279bed98673dd5bef374d3b6e4b09e2af76183bf"
version = "v1.0.0-rc1"
[[projects]]
digest = "1:bbd3997f0121200f72b64d7a3826eb8a0b910d6a4c19894c9fe2852b9e5eaf3b"
digest = "1:93131d8002d7025da13582877c32d1fc302486775a1b06f62241741006428c5e"
name = "github.com/pelletier/go-toml"
packages = ["."]
pruneopts = "UT"
revision = "8fe62057ea2d46ce44254c98e84e810044dbe197"
version = "v1.5.0"
revision = "728039f679cbcd4f6a54e080d2219a4c4928c546"
version = "v1.4.0"
[[projects]]
digest = "1:cf31692c14422fa27c83a05292eb5cbe0fb2775972e8f1f8446a71549bd8980b"
@@ -443,14 +352,6 @@
revision = "ba968bfe8b2f7e042a574c888954fccecfa385b4"
version = "v0.8.1"
[[projects]]
digest = "1:0028cb19b2e4c3112225cd871870f2d9cf49b9b4276531f03438a88e94be86fe"
name = "github.com/pmezard/go-difflib"
packages = ["difflib"]
pruneopts = "UT"
revision = "792786c7400a136282c1664665ae0a8db921c6c2"
version = "v1.0.0"
[[projects]]
digest = "1:7d99649602f68b73ade640ca6975ccc38735f329e159c6a507b63f00213678c0"
name = "github.com/pressly/goose"
@@ -468,12 +369,15 @@
revision = "cac0b30c2563378d434b5af411844adff8e32960"
[[projects]]
digest = "1:274f67cb6fed9588ea2521ecdac05a6d62a8c51c074c1fccc6a49a40ba80e925"
name = "github.com/satori/go.uuid"
packages = ["."]
digest = "1:ab1672baf07ee80c988e369e5633bcac459342e8e00d0c38a799056395fe9dba"
name = "github.com/shirou/gopsutil"
packages = [
"cpu",
"internal/common",
]
pruneopts = "UT"
revision = "f58768cc1a7a7e77a3bd49e98cdd21419399b6a3"
version = "v1.2.0"
revision = "e4ec7b275ada47ca32799106c2dba142d96aaf93"
version = "v2.19.8"
[[projects]]
digest = "1:04457f9f6f3ffc5fea48e71d62f2ca256637dee0a04d710288e27e05c8b41976"
@@ -511,37 +415,21 @@
version = "v1.1.0"
[[projects]]
digest = "1:524b71991fc7d9246cc7dc2d9e0886ccb97648091c63e30eef619e6862c955dd"
digest = "1:c1b1102241e7f645bc8e0c22ae352e8f0dc6484b6cb4d132fa9f24174e0119e2"
name = "github.com/spf13/pflag"
packages = ["."]
pruneopts = "UT"
revision = "2e9d26c8c37aae03e3f9d4e90b7116f5accb7cab"
version = "v1.0.5"
revision = "298182f68c66c05229eb03ac171abe6e309ee79a"
version = "v1.0.3"
[[projects]]
digest = "1:0b60fc944fb6a7b6c985832bd341bdb7ed8fe894fea330414e7774bb24652962"
digest = "1:11118bd196646c6515fea3d6c43f66162833c6ae4939bfb229b9956d91c6cf17"
name = "github.com/spf13/viper"
packages = ["."]
pruneopts = "UT"
revision = "72b022eb357a56469725dcd03918449e2278d02e"
version = "v1.5.0"
[[projects]]
digest = "1:8548c309c65a85933a625be5e7d52b6ac927ca30c56869fae58123b8a77a75e1"
name = "github.com/stretchr/testify"
packages = ["assert"]
pruneopts = "UT"
revision = "221dbe5ed46703ee255b1da0dec05086f5035f62"
revision = "b5bf975e5823809fb22c7644d008757f78a4259e"
version = "v1.4.0"
[[projects]]
digest = "1:f4b32291cad5efac2bfdba89ccde6aa04618b62ce06c1a571da2dc4f3f2677fb"
name = "github.com/subosito/gotenv"
packages = ["."]
pruneopts = "UT"
revision = "2ef7124db659d49edac6aa459693a15ae36c671a"
version = "v1.2.0"
[[projects]]
branch = "master"
digest = "1:d32b64a7a82dd36b674fb73ff767e949eb7155b6b574ff276f49d4edc8af105f"
@@ -560,7 +448,7 @@
[[projects]]
branch = "master"
digest = "1:77f7e2f75e4c44ede24f47aca6c514f24f06c6a0ee3c47c8d7ce2b77b49ac482"
digest = "1:b97ba937497c9b282245aa8f633212c96fcaa1b4cc30e9ab6ae41a0168e32c35"
name = "github.com/valyala/fasthttp"
packages = [
".",
@@ -568,69 +456,53 @@
"stackless",
]
pruneopts = "UT"
revision = "9bc6da12192c610a272a9289b9574eb5d8cfdfe1"
revision = "8713335f548d2c18effe36c9686f5a88b65eefce"
[[projects]]
digest = "1:39a425f98fb19427061a693fe6bf0683c9bddec4b25b17067e34fdb465e39cb9"
name = "github.com/x-cray/logrus-prefixed-formatter"
packages = ["."]
pruneopts = "UT"
revision = "bb2702d423886830dee131692131d35648c382e2"
version = "v0.5.2"
[[projects]]
branch = "master"
digest = "1:87fe9bca786484cef53d52adeec7d1c52bc2bfbee75734eddeb75fc5c7023871"
name = "github.com/xeipuuv/gojsonpointer"
packages = ["."]
pruneopts = "UT"
revision = "02993c407bfbf5f6dae44c4f4b1cf6a39b5fc5bb"
[[projects]]
branch = "master"
digest = "1:dc6a6c28ca45d38cfce9f7cb61681ee38c5b99ec1425339bfc1e1a7ba769c807"
name = "github.com/xeipuuv/gojsonreference"
packages = ["."]
pruneopts = "UT"
revision = "bd5ef7bd5415a7ac448318e64f11a24cd21e594b"
[[projects]]
digest = "1:a8a0ed98532819a3b0dc5cf3264a14e30aba5284b793ba2850d6f381ada5f987"
name = "github.com/xeipuuv/gojsonschema"
packages = ["."]
pruneopts = "UT"
revision = "82fcdeb203eb6ab2a67d0a623d9c19e5e5a64927"
version = "v1.2.0"
[[projects]]
branch = "master"
digest = "1:f92f6956e4059f6a3efc14924d2dd58ba90da25cc57fe07ae3779ef2f5e0c5f2"
digest = "1:35ce874cf16f78a2da908ab28b0277497e36603d289db00d39da5200bc8ace08"
name = "golang.org/x/crypto"
packages = ["pbkdf2"]
packages = [
"pbkdf2",
"ssh/terminal",
]
pruneopts = "UT"
revision = "87dc89f01550277dc22b74ffcf4cd89fa2f40f4c"
revision = "9756ffdc24725223350eb3266ffb92590d28f278"
[[projects]]
branch = "master"
digest = "1:60dc5bc60f5ec42121f8b90de6f86bd1f708b6422114a02012395d43e377e757"
digest = "1:8c8471f63317e39731853a4f55d5d8ff43a142aa425a666a0554bdba0a8b7f8b"
name = "golang.org/x/net"
packages = [
"context",
"context/ctxhttp",
"http/httpguts",
"http2",
"http2/hpack",
"idna",
"internal/socks",
"internal/timeseries",
"proxy",
"trace",
]
pruneopts = "UT"
revision = "ec77196f6094c3492a8b61f2c11cf937f78992ae"
revision = "ba9fcec4b297b415637633c5a6e8fa592e4a16c3"
[[projects]]
branch = "master"
digest = "1:de0084adc1c0b8cf6fd192d7785b098b155ba355cbeec9ee361aea55b887ab9d"
digest = "1:4f9cc50343843f7c58c1a1aecf17c226ea0e855f4d3293e796701ae985111e0d"
name = "golang.org/x/sys"
packages = [
"unix",
"windows",
]
pruneopts = "UT"
revision = "53bf42e6b339f7ed00535fc6915737b3959eac89"
revision = "749cb33beabd9aa6d3178e3de05bcc914f70b2bf"
[[projects]]
digest = "1:8d8faad6b12a3a4c819a3f9618cb6ee1fa1cfc33253abeeea8b55336721e3405"
@@ -659,17 +531,20 @@
[[projects]]
branch = "master"
digest = "1:a910255c3b706b4d8f2b185ed6b40c8f31b805111be240def2bdf2c62b87591b"
digest = "1:08aa0c3a326b71c5afe441683697766f6b172f652b919ecd114881a7f7581a4d"
name = "google.golang.org/genproto"
packages = [
"googleapis/api/annotations",
"googleapis/api/httpbody",
"googleapis/rpc/errdetails",
"googleapis/rpc/status",
"protobuf/field_mask",
]
pruneopts = "UT"
revision = "548a555dbc03994223efbaba0090152849259498"
revision = "92dd089d5514cecde7a465f807541f83dfd486d5"
[[projects]]
digest = "1:6cd77d0b616d2dcebd363dfecba593f27b0151fc82cdb5fbfb96c5a7cfbc95b5"
digest = "1:3b97661db2e5d4c87f7345e875ea28f911e54c715ba0a74be08e1649d67e05cd"
name = "google.golang.org/grpc"
packages = [
".",
@@ -707,16 +582,16 @@
"tap",
]
pruneopts = "UT"
revision = "f6d0f9ee430895e87ef1ceb5ac8f39725bafceef"
version = "v1.24.0"
revision = "6eaf6f47437a6b4e2153a190160ef39a92c7eceb"
version = "v1.23.0"
[[projects]]
digest = "1:59f10c1537d2199d9115d946927fe31165959a95190849c82ff11e05803528b0"
digest = "1:4d2e5a73dc1500038e504a8d78b986630e3626dc027bc030ba5c75da257cdb96"
name = "gopkg.in/yaml.v2"
packages = ["."]
pruneopts = "UT"
revision = "f221b8435cfb71e54062f6c6e99e9ade30b124d5"
version = "v2.2.4"
revision = "51d6538a90f86fe93ac480b35f37b2be17fef232"
version = "v2.2.2"
[[projects]]
digest = "1:999d566ad1ae4303c456af5a155f7b42401cca4fd33552567ed9dd997b107a08"
@@ -727,18 +602,6 @@
source = "https://github.com/mellium/sasl.git"
version = "v0.2.1"
[[projects]]
digest = "1:25ea8c84118bb09a6ea1fe5d8a2e72d7ead40af714b74d1e849af821f3502414"
name = "nhooyr.io/websocket"
packages = [
".",
"internal/bpool",
"internal/wsjs",
]
pruneopts = "UT"
revision = "edda9c633d5c78c7d38fcc952b4105dd4ccfb619"
version = "v1.7.4"
[solve-meta]
analyzer-name = "dep"
analyzer-version = 1
@@ -746,37 +609,28 @@
"github.com/asaskevich/govalidator",
"github.com/cenkalti/backoff",
"github.com/go-pg/pg",
"github.com/hashicorp/go-hclog",
"github.com/hashicorp/raft",
"github.com/hashicorp/raft-boltdb",
"github.com/integration-system/bellows",
"github.com/integration-system/isp-etp-go",
"github.com/integration-system/isp-etp-go/client",
"github.com/integration-system/isp-lib-test/ctx",
"github.com/integration-system/isp-lib-test/docker",
"github.com/integration-system/isp-lib-test/utils",
"github.com/integration-system/isp-lib-test/utils/postgres",
"github.com/integration-system/isp-lib/atomic",
"github.com/go-pg/pg/orm",
"github.com/golang/protobuf/proto",
"github.com/golang/protobuf/ptypes/struct",
"github.com/googollee/go-engine.io",
"github.com/googollee/go-socket.io",
"github.com/grpc-ecosystem/grpc-gateway/runtime",
"github.com/grpc-ecosystem/grpc-gateway/utilities",
"github.com/integration-system/isp-lib/backend",
"github.com/integration-system/isp-lib/bootstrap",
"github.com/integration-system/isp-lib/config",
"github.com/integration-system/isp-lib/config/schema",
"github.com/integration-system/isp-lib/database",
"github.com/integration-system/isp-lib/logger",
"github.com/integration-system/isp-lib/metric",
"github.com/integration-system/isp-lib/structure",
"github.com/integration-system/isp-lib/utils",
"github.com/integration-system/isp-log",
"github.com/integration-system/isp-log/stdcodes",
"github.com/json-iterator/go",
"github.com/mohae/deepcopy",
"github.com/pkg/errors",
"github.com/satori/go.uuid",
"github.com/sirupsen/logrus",
"github.com/spf13/cast",
"github.com/stretchr/testify/assert",
"github.com/thecodeteam/goodbye",
"github.com/xeipuuv/gojsonschema",
"github.com/valyala/fasthttp",
"golang.org/x/net/context",
"google.golang.org/genproto/googleapis/api/annotations",
"google.golang.org/grpc",
"google.golang.org/grpc/codes",
"google.golang.org/grpc/grpclog",
"google.golang.org/grpc/status",
]
solver-name = "gps-cdcl"
+6 -2
View File
@@ -37,5 +37,9 @@
branch = "master"
[[override]]
name = "github.com/hashicorp/raft"
branch = "master"
name = "github.com/googollee/go-socket.io"
revision = "c8aeb1ed9b49d7de8fef8662efb18f1d289c5f2e"
[[override]]
name = "github.com/googollee/go-engine.io"
revision = "e2f255711dcb2ea41e42c6d9d98c172d7edf6509"
+92
View File
@@ -0,0 +1,92 @@
## Contents
## [1. Installing](#installing)
## [2. Using](#using)
## [3. Environment variables](#environment-variables)
## Installing
### 1. Download dependencies
```
go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway
go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger
go get -u github.com/golang/protobuf/protoc-gen-go
```
### 2. Generate GRPC, GRPC-gateway, GRPC-gateway-swagger
###### WINDOWS
```cmd
protoc ^
-I. -I%GOPATH%\src ^
-I%GOPATH%\src\github.com\grpc-ecosystem\grpc-gateway\third_party\googleapis ^
--go_out=plugins=grpc:. --grpc-gateway_out=logtostderr=true:. --swagger_out=logtostderr=true:. ^
proto\config_service.proto
```
###### LINUX
```bash
protoc -I. \
-I$GOPATH \
-I$GOPATH/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
--go_out=plugins=grpc:. --grpc-gateway_out=logtostderr=true:. --swagger_out=logtostderr=true:. \
proto/config_service.proto
```
## Using
### 1. GRPC
Default GRPC port is: `5001`, might be changed in config file
Proto file is: `proto/config_service.proto`
### 2. REST proxy to GRPC
Default port is: `5000`, might be changed in config file
Swagger work on http://0.0.0.0:5000/swagger
### 3. SocketIO
For connect to this server two variables must be sent in query path:
1. `module_name` - Module name, for example `auth`.
2. `instance_uuid` - UUID - instance identity.
#### Events
##### Event to a client
`CONFIG:SEND_CONFIG_WHEN_CONNECTED` - When a connection is established to a client will send an event.
`CONFIG:SEND_CONFIG_CHANGED` - When config for particular module had been changed this event with new config will send to a client.
`CONFIG:SEND_CONFIG_ON_REQUEST` - the server will send to a client actual config with this event after `CONFIG:REQUEST_CONFIG`
###### The next events work on both sides. First, when new backend publishes new methods at config service there is incoming one of this events:
`ROUTES:SEND_ROUTES_WHEN_CONNECTED` - A backend sends this event when a connection is established with a config server.
`ROUTES:SEND_ROUTES_CHANGED` - Any module can say that something had changed in its methods.
`ROUTES:SEND_ROUTES_ON_REQUEST` - A config service is able to make a request to renew list methods.
###### A config service, in turn, send the same events types in each its connection.
For all of this events we wait for next data structure:
```json
{
"address": {
"ip": "10.10.10.10",
"port": "5001"
},
"endpoints": [
{"path": "/api/user/get"},
{"path": "/api/user/save"},
{"path": "/api/user/delete"}
]
}
```
##### Event to the server
`CONFIG:REQUEST_CONFIG` - A client can request current config with this event.
## Environment variables
`APP_PROFILE` - Name for config file, default is `config`. Will seek file with name: `config.yml`.
`APP_CONFIG_PATH` - Absolute path where a config file is. If a variable hadn't been specified config will seek into the same directory, when binary file placed.
`LOG_LEVEL` - Log level, the default is `INFO`.
`APP_MODE` - If set to `dev` logger for SQL will be on and if `LOG_LEVEL` hadn't been specified it will set to `DEBUG`.
## Changes
#### 0.2.2 - 2018-10-05
- Add default config for mdm module
-187
View File
@@ -1,187 +0,0 @@
package cluster
import (
"errors"
"github.com/integration-system/isp-lib/structure"
"github.com/integration-system/isp-lib/utils"
log "github.com/integration-system/isp-log"
jsoniter "github.com/json-iterator/go"
"isp-config-service/codes"
"isp-config-service/entity"
"isp-config-service/raft"
"isp-config-service/store/state"
"sync"
"time"
)
var (
ErrNoLeader = errors.New("no leader in cluster")
ErrLeaderClientNotInitialized = errors.New("leader client not initialized")
ErrNotLeader = errors.New("node is not a leader")
json = jsoniter.ConfigFastest
)
const (
leaderConnectionTimeout = 3 * time.Second
defaultApplyTimeout = 3 * time.Second
)
type Client struct {
r *raft.Raft
leaderMu sync.RWMutex
leaderState leaderState
leaderClient *SocketLeaderClient
declaration structure.BackendDeclaration
onClientDisconnect func(string)
}
func (client *Client) Shutdown() error {
client.leaderMu.Lock()
defer client.leaderMu.Unlock()
if client.leaderClient != nil {
client.leaderClient.Close()
client.leaderClient = nil
}
return client.r.GracefulShutdown()
}
func (client *Client) IsLeader() bool {
client.leaderMu.RLock()
defer client.leaderMu.RUnlock()
return client.leaderState.isLeader
}
func (client *Client) SyncApply(command []byte) (*ApplyLogResponse, error) {
client.leaderMu.RLock()
defer client.leaderMu.RUnlock()
if !client.leaderState.leaderElected {
return nil, ErrNoLeader
}
if client.leaderState.isLeader {
apply, err := client.r.SyncApply(command)
if err != nil {
return nil, err
}
logResponse := apply.(ApplyLogResponse)
return &logResponse, err
} else {
if client.leaderClient == nil {
return nil, ErrLeaderClientNotInitialized
}
response, err := client.leaderClient.Ack(command, defaultApplyTimeout)
if err != nil {
return nil, err
}
var logResponse ApplyLogResponse
err = json.Unmarshal(response, &logResponse)
if err != nil {
return nil, err
}
return &logResponse, nil
}
}
func (client *Client) SyncApplyOnLeader(command []byte) (*ApplyLogResponse, error) {
client.leaderMu.RLock()
defer client.leaderMu.RUnlock()
if !client.leaderState.isLeader {
return nil, ErrNotLeader
}
apply, err := client.r.SyncApply(command)
if err != nil {
return nil, err
}
logResponse := apply.(ApplyLogResponse)
return &logResponse, err
}
func (client *Client) listenLeader() {
for n := range client.r.LeaderCh() {
client.leaderMu.Lock()
if client.leaderClient != nil {
log.Debugf(0, "close previous leader ws connection %s", client.leaderState.leaderAddr)
client.leaderClient.Close()
client.leaderClient = nil
}
if n.LeaderElected && !n.IsLeader {
leaderClient := NewSocketLeaderClient(n.CurrentLeaderAddress, func() {
client.onClientDisconnect(client.leaderState.leaderAddr)
})
if err := leaderClient.Dial(leaderConnectionTimeout); err != nil {
log.Fatalf(codes.LeaderClientConnectionError, "could not connect to leader: %v", err)
continue
}
client.leaderClient = leaderClient
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)
} else if response != utils.WsOkResponse {
log.Warnf(codes.SendDeclarationToLeaderError, "send declaration to leader. response: %s", response)
}
}(client.declaration)
} else if n.LeaderElected && n.IsLeader {
go func(declaration structure.BackendDeclaration) {
now := state.GenerateDate()
module := entity.Module{
Id: state.GenerateId(),
Name: declaration.ModuleName,
CreatedAt: now,
LastConnectedAt: now,
}
command := PrepareModuleConnectedCommand(module)
syncApplyCommand(client, command, "ModuleConnectedCommand")
declarationCommand := PrepareUpdateBackendDeclarationCommand(declaration)
syncApplyCommand(client, declarationCommand, "UpdateBackendDeclarationCommand")
}(client.declaration)
}
client.leaderState = leaderState{
leaderElected: n.LeaderElected,
isLeader: n.IsLeader,
leaderAddr: n.CurrentLeaderAddress,
}
client.leaderMu.Unlock()
}
}
type leaderState struct {
leaderElected bool
isLeader bool
leaderAddr string
}
func NewRaftClusterClient(r *raft.Raft, declaration structure.BackendDeclaration, onLeaderDisconnect func(string)) *Client {
client := &Client{
r: r,
declaration: declaration,
leaderState: leaderState{},
onClientDisconnect: onLeaderDisconnect,
}
go client.listenLeader()
return client
}
func syncApplyCommand(clusterClient *Client, command []byte, commandName string) {
applyLogResponse, err := clusterClient.SyncApply(command)
if err != nil {
log.Warnf(codes.SyncApplyError, "announce myself. apply %s: %v", commandName, err)
}
if applyLogResponse != nil && applyLogResponse.ApplyError != "" {
log.WithMetadata(map[string]interface{}{
"result": string(applyLogResponse.Result),
"applyError": applyLogResponse.ApplyError,
"commandName": commandName,
}).Warnf(codes.SyncApplyError, "announce myself. apply command")
}
}
-90
View File
@@ -1,90 +0,0 @@
package cluster
import (
"bytes"
"encoding/binary"
"github.com/integration-system/isp-lib/structure"
log "github.com/integration-system/isp-log"
"isp-config-service/codes"
"isp-config-service/entity"
"time"
)
const (
ApplyCommandEvent = "CONFIG_CLUSTER:APPLY_COMMAND"
ClusterParam = "cluster"
)
const (
_ = iota
UpdateBackendDeclarationCommand
DeleteBackendDeclarationCommand
UpdateConfigSchemaCommand
ModuleConnectedCommand
ModuleDisconnectedCommand
DeleteModulesCommand
ActivateConfigCommand
DeleteConfigsCommand
UpsertConfigCommand
DeleteCommonConfigsCommand
UpsertCommonConfigCommand
)
func PrepareUpdateBackendDeclarationCommand(backend structure.BackendDeclaration) []byte {
return prepareCommand(UpdateBackendDeclarationCommand, backend)
}
func PrepareDeleteBackendDeclarationCommand(backend structure.BackendDeclaration) []byte {
return prepareCommand(DeleteBackendDeclarationCommand, backend)
}
func PrepareModuleConnectedCommand(module entity.Module) []byte {
return prepareCommand(ModuleConnectedCommand, module)
}
func PrepareModuleDisconnectedCommand(module entity.Module) []byte {
return prepareCommand(ModuleDisconnectedCommand, module)
}
func PrepareDeleteModulesCommand(ids []string) []byte {
return prepareCommand(DeleteModulesCommand, DeleteModules{Ids: ids})
}
func PrepareActivateConfigCommand(configId string, date time.Time) []byte {
return prepareCommand(ActivateConfigCommand, ActivateConfig{ConfigId: configId, Date: date})
}
func PrepareDeleteConfigsCommand(ids []string) []byte {
return prepareCommand(DeleteConfigsCommand, DeleteModules{Ids: ids})
}
func PrepareUpsertConfigCommand(config UpsertConfig) []byte {
return prepareCommand(UpsertConfigCommand, config)
}
func PrepareUpdateConfigSchemaCommand(schema entity.ConfigSchema) []byte {
return prepareCommand(UpdateConfigSchemaCommand, schema)
}
func PrepareDeleteCommonConfigsCommand(id string) []byte {
return prepareCommand(DeleteCommonConfigsCommand, DeleteCommonConfig{Id: id})
}
func PrepareUpsertCommonConfigCommand(config UpsertCommonConfig) []byte {
return prepareCommand(UpsertCommonConfigCommand, config)
}
func prepareCommand(command uint64, payload interface{}) []byte {
cmd := make([]byte, 8)
binary.BigEndian.PutUint64(cmd, command)
buf := bytes.NewBuffer(cmd)
err := json.NewEncoder(buf).Encode(payload)
if err != nil {
log.Fatalf(codes.PrepareLogCommandError, "prepare log command: %v", err)
}
return buf.Bytes()
}
-65
View File
@@ -1,65 +0,0 @@
package cluster
import (
json2 "encoding/json"
"fmt"
"google.golang.org/grpc/codes"
"isp-config-service/entity"
"time"
)
type ApplyLogResponse struct {
ApplyError string
Result json2.RawMessage
}
func (a ApplyLogResponse) Error() string {
return a.ApplyError
}
type DeleteModules struct {
Ids []string
}
type ActivateConfig struct {
ConfigId string
Date time.Time
}
type UpsertConfig struct {
Config entity.Config
Create bool
Unsafe bool
}
type DeleteConfigs struct {
Ids []string
}
type DeleteCommonConfig struct {
Id string
}
type UpsertCommonConfig struct {
Config entity.CommonConfig
Create bool
}
type ResponseWithError struct {
Response interface{}
Error string
ErrorCode codes.Code
}
func NewResponseErrorf(code codes.Code, format string, args ...interface{}) ResponseWithError {
return ResponseWithError{
Error: fmt.Sprintf(format, args...),
ErrorCode: code,
}
}
func NewResponse(value interface{}) ResponseWithError {
return ResponseWithError{
Response: value,
}
}
-106
View File
@@ -1,106 +0,0 @@
package cluster
import (
"context"
"fmt"
"github.com/cenkalti/backoff"
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"
log "github.com/integration-system/isp-log"
"isp-config-service/codes"
"isp-config-service/conf"
"net"
"net/http"
"net/url"
"time"
)
type SocketLeaderClient struct {
client etp.Client
url string
globalCtx context.Context
cancel context.CancelFunc
}
func (c *SocketLeaderClient) Ack(data []byte, timeout time.Duration) ([]byte, error) {
ctx, cancel := context.WithTimeout(c.globalCtx, timeout)
defer cancel()
response, err := c.client.EmitWithAck(ctx, ApplyCommandEvent, data)
return response, err
}
func (c *SocketLeaderClient) SendDeclaration(backend structure.BackendDeclaration, timeout time.Duration) (string, error) {
data, err := json.Marshal(backend)
if err != nil {
return "", err
}
ctx, cancel := context.WithTimeout(c.globalCtx, timeout)
defer cancel()
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
bf := backoff.WithContext(backOff, c.globalCtx)
dial := func() error {
return c.client.Dial(c.globalCtx, c.url)
}
return backoff.Retry(dial, bf)
}
func (c *SocketLeaderClient) 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 {
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{}{
"leaderAddr": address,
}).Warn(codes.LeaderClientDisconnected, "leader client disconnected")
leaderDisconnectionCallback()
})
leaderClient.client.OnError(func(err error) {
log.Warnf(codes.LeaderClientConnectionError, "leader client on error: %v", err)
})
leaderClient.client.OnConnect(func() {
log.Debug(0, "leader client connected")
})
return leaderClient
}
func getUrl(address string) string {
addr, err := net.ResolveTCPAddr("tcp", address)
if err != nil {
panic(err) // must never occurred
}
cfg := config.Get().(*conf.Configuration)
params := url.Values{}
params.Add(ClusterParam, "true")
// TODO выпилить instance_uuid ?
params.Add(utils.ModuleNameGetParamKey, cfg.ModuleName)
params.Add(utils.InstanceUuidGetParamKey, "9d89354b-c728-4b48-b002-a7d3b229f151")
return fmt.Sprintf("ws://%s:%d/isp-etp/?%s", addr.IP.String(), addr.Port, params.Encode())
}
-39
View File
@@ -1,39 +0,0 @@
package codes
const (
// Common
StartHttpServerError = 1001
ShutdownHttpServerError = 1002
ShutdownHttpServerInfo = 1003
WebsocketError = 1004
WebsocketEmitError = 1005
DatabaseOperationError = 1006
// Raft
InitRaftError = 1007
RestoreFromRepositoryError = 1008
RaftLoggerCode = 1009
BootstrapClusterError = 1010
RaftShutdownError = 1011
RaftShutdownInfo = 1012
// Raft Log
ApplyLogCommandError = 1013
PrepareLogCommandError = 1014
SyncApplyError = 1015
// Raft Cluster
SendDeclarationToLeaderError = 1016
LeaderClientConnectionError = 1017
LeaderClientDisconnected = 1018
// Services
DiscoveryServiceSendModulesError = 1019
RoutesServiceSendRoutesError = 1020
ConfigServiceBroadcastConfigError = 1021
// Mux
InitMuxError = 1022
)
+4 -13
View File
@@ -1,15 +1,15 @@
database:
address: "127.0.0.1"
schema: "config_service"
database: "test"
database: "isp"
port: "5432"
username: "test"
password: "password"
username: "isp"
password: "isp_password"
createSchema: true
moduleName: "config"
grpcOuterAddress:
ip: ""
ip: 127.0.0.1
port: 9002
ws:
@@ -28,12 +28,3 @@ metrics:
ip: "0.0.0.0"
port: "9551"
path: "/metrics"
cluster:
dataDir: ./data
inMemory: true
outerAddress: 127.0.0.1:9001
connectTimeoutSeconds: 5
bootstrapCluster: true
peers:
- 127.0.0.1:9001
-10
View File
@@ -1,10 +0,0 @@
moduleName: config
instanceUuid: bf482806-0c3d-4e0d-b9d4-12c037b12d70
registry:
host: nexus.msp.mobi
username: mp3deployer
password: ScjKLQuvqfAXu2bs8ysLAvRt
images:
module: nexus.msp.mobi/msp2/dev/isp-config-service:latest
+6 -19
View File
@@ -5,25 +5,12 @@ import (
)
type Configuration struct {
Database structure.DBConfiguration `valid:"required~Required" schema:"База данных,настройка параметров подключения к базе данных"`
Database structure.DBConfiguration `valid:"required~Required"`
GrpcOuterAddress structure.AddressConfiguration `valid:"required~Required" json:"grpcOuterAddress"`
ModuleName string `valid:"required~Required"`
WS WebService `valid:"required~Required" schema:"Конфигурация веб сервиса"`
Metrics structure.MetricConfiguration
Cluster ClusterConfiguration `valid:"required~Required"`
}
type ClusterConfiguration struct {
InMemory bool `schema:"Хранить логи и снэпшоты только в памяти"`
DataDir string `valid:"required~Required" schema:"Пусть до директории для логов и снэпшотов рафта"`
BootstrapCluster bool `schema:"Поднимать кластер и объявлять лидером"`
Peers []string `valid:"required~Required" schema:"Адреса всех нод в кластере,формат address:port"`
OuterAddress string `valid:"required~Required" schema:"Внешний адрес ноды"`
ConnectTimeoutSeconds int `valid:"required~Required" schema:"Таймаут подключения"`
}
type WebService struct {
Rest structure.AddressConfiguration `valid:"required~Required"`
Grpc structure.AddressConfiguration `valid:"required~Required"`
WsConnectionReadLimitKB int64 `schema:"Максимальное количество килобайт на чтение по вебсокету,при превышении соединение закрывается с ошибкой"`
WS struct {
Rest structure.AddressConfiguration `valid:"required~Required"`
Grpc structure.AddressConfiguration `valid:"required~Required"`
}
Metrics structure.MetricConfiguration
}
-320
View File
@@ -1,320 +0,0 @@
package main
import (
"bytes"
"fmt"
"github.com/integration-system/isp-lib-test/ctx"
"github.com/integration-system/isp-lib-test/docker"
"github.com/integration-system/isp-lib-test/utils"
"github.com/integration-system/isp-lib-test/utils/postgres"
"github.com/integration-system/isp-lib/backend"
"github.com/integration-system/isp-lib/structure"
"github.com/stretchr/testify/assert"
"google.golang.org/grpc"
"io"
"io/ioutil"
"isp-config-service/conf"
"isp-config-service/domain"
"log"
"net"
"strconv"
"strings"
"testing"
"time"
)
const (
configServiceHttpPort = "9001"
configServiceGrpcPort = "9002"
configServiceSchema = "config_service"
configsNumber = 3
maxAwaitingTime = 25 * time.Second
deleteCommonConfigsCommand = "config/common_config/delete_config"
getRoutesCommand = "config/routing/get_routes"
)
var (
pgCfg structure.DBConfiguration
configsHttpAddrs = make([]structure.AddressConfiguration, configsNumber)
configsGrpcAddrs = make([]structure.AddressConfiguration, configsNumber)
configsCtxs = make([]*docker.ContainerContext, configsNumber)
)
func TestMain(m *testing.M) {
cfg := ctx.BaseTestConfiguration{}
test, err := ctx.NewIntegrationTest(m, &cfg, setup)
if err != nil {
panic(err)
}
test.PrepareAndRun()
}
func setup(testCtx *ctx.TestContext, runTest func() int) int {
cfg := testCtx.BaseConfiguration()
cli, err := docker.NewClient()
if err != nil {
panic(err)
}
defer cli.Close()
env := docker.NewTestEnvironment(testCtx, cli)
defer env.Cleanup()
_, pgCfg = env.RunPGContainer()
_, err = postgres.Wait(pgCfg, 10*time.Second)
if err != nil {
panic(err)
}
pgCfg.Schema = configServiceSchema
configs := make([]conf.Configuration, configsNumber)
peersAddrs := make([]string, configsNumber)
for i := 0; i < configsNumber; i++ {
httpAddr := getConfigServiceAddress(i, configServiceHttpPort)
grpcAddr := getConfigServiceAddress(i, configServiceGrpcPort)
cfg := conf.Configuration{
Database: pgCfg,
ModuleName: moduleName,
GrpcOuterAddress: grpcAddr,
WS: conf.WebService{
Rest: httpAddr,
Grpc: grpcAddr,
},
Cluster: conf.ClusterConfiguration{
InMemory: false,
DataDir: "./data",
Peers: nil,
OuterAddress: httpAddr.GetAddress(),
ConnectTimeoutSeconds: 10,
BootstrapCluster: false,
},
}
configsGrpcAddrs[i] = grpcAddr
configsHttpAddrs[i] = httpAddr
configs[i] = cfg
peersAddrs[i] = httpAddr.GetAddress()
}
configs[0].Cluster.BootstrapCluster = true
for i := 0; i < configsNumber; i++ {
c := configs[i]
peersAddrsEnv := generatePeersConfigEnv(peersAddrs)
peersAddrsEnv["LOG_LEVEL"] = "debug"
ctx := env.RunAppContainer(
cfg.Images.Module, c, nil,
docker.WithName(c.GrpcOuterAddress.IP),
docker.WithLogger(NewWriteLogger(strconv.Itoa(i)+"_config:", ioutil.Discard, "DeleteCommonConfigsCommand")),
//docker.PullImage(cfg.Registry.Username, cfg.Registry.Password),
docker.WithEnv(peersAddrsEnv),
)
grpcAddr := configsGrpcAddrs[i]
grpcAddr.IP = ctx.GetIPAddress()
configsGrpcAddrs[i] = grpcAddr
httpAddr := configsHttpAddrs[i]
httpAddr.IP = ctx.GetIPAddress()
configsHttpAddrs[i] = httpAddr
configsCtxs[i] = ctx
}
//time.Sleep(3 * time.Second)
return runTest()
}
func TestClusterElection(t *testing.T) {
defer func() {
err := recover()
if err != nil {
log.Println(err)
}
}()
a := assert.New(t)
var ready bool
ready = testClusterReady(a, -1)
if !ready {
return
}
for i := 0; i < configsNumber; i++ {
fmt.Print("\n\n\n")
log.Printf("stopping %d container\n", i)
a.NoError(configsCtxs[i].StopContainer(20 * time.Second))
time.Sleep(5 * time.Second)
fmt.Print("\n\n\n")
log.Printf("checking cluster except %d\n", i)
ready = testClusterReady(a, i)
if !ready {
return
}
fmt.Print("\n\n\n")
log.Printf("starting %d container\n", i)
a.NoError(configsCtxs[i].StartContainer())
time.Sleep(3 * time.Second)
log.Printf("checking cluster, iteration %d\n", i+1)
ready = testClusterReady(a, -1)
if !ready {
return
}
}
}
func getConfigServiceAddress(num int, port string) structure.AddressConfiguration {
lastIp := pgCfg.Address
ip := net.ParseIP(lastIp).To4()
ip[3] = byte(int(ip[3]) + num + 1)
return structure.AddressConfiguration{
//IP: fmt.Sprintf("%s-%d", "isp-config-service", num),
IP: ip.String(),
Port: port,
}
}
func testClusterReady(a *assert.Assertions, except int) bool {
var clients []*backend.InternalGrpcClient
defer func() {
for _, client := range clients {
client.CloseQuietly()
}
}()
for j := 0; j < configsNumber; j++ {
if j == except {
continue
}
configAddr := configsGrpcAddrs[j]
client := testGrpcReady(configAddr, a)
if client == nil {
a.Fail(fmt.Sprintf("unable to connect to %d config", j))
return false
}
clients = append(clients, client)
ready := testRaftReady(client, a)
if !ready {
return ready
}
}
prevRoutes := getRoutes(clients[0], a)
routesLen := len(clients)
for i := 1; i < len(clients); i++ {
routes := getRoutes(clients[i], a)
t := a.Len(routes, routesLen, "invalid length")
if !t {
return t
}
match := a.ElementsMatch(prevRoutes, routes, "different backend declarations")
if !match {
return match
}
}
return true
}
func testGrpcReady(configAddr structure.AddressConfiguration, a *assert.Assertions) *backend.InternalGrpcClient {
start := time.Now()
var client *backend.InternalGrpcClient
var err error
_, _ = await(func() (interface{}, error) {
client, err = backend.NewGrpcClient(
configAddr.GetAddress(),
grpc.WithBlock(),
grpc.WithInsecure(),
)
//log.Println("connect to grpc err:", err)
return nil, err
}, maxAwaitingTime)
if !a.NoError(err) {
return nil
}
log.Println("waiting until grpc ready:", time.Now().Sub(start).Round(time.Second))
return client
}
func testRaftReady(client *backend.InternalGrpcClient, a *assert.Assertions) bool {
var err error
req := new(domain.ConfigIdRequest)
req.Id = "33"
response := new(structure.GrpcError)
start := time.Now()
f := func() (interface{}, error) {
err = client.Invoke(
deleteCommonConfigsCommand,
-1,
req,
response,
)
//log.Println("send grpc request. response: ", response, "err: ", err)
return nil, err
}
_, _ = await(f, maxAwaitingTime)
log.Println("waiting until raft ready:", time.Now().Sub(start).Round(time.Second))
return a.NoError(err)
}
func getRoutes(client *backend.InternalGrpcClient, a *assert.Assertions) []structure.BackendDeclaration {
var response []structure.BackendDeclaration
err := client.Invoke(
getRoutesCommand,
-1,
nil,
&response,
)
//log.Println("routes:", response)
a.NoError(err)
return response
}
func await(dialer func() (interface{}, error), timeout time.Duration) (interface{}, error) {
retryer := utils.NewRetryer(dialer, timeout)
retryer.AttemptTimeout = 300 * time.Millisecond
return retryer.Do()
}
func generatePeersConfigEnv(peers []string) map[string]string {
key := "LC_ISP_CLUSTER.PEERS"
val := strings.Join(peers, ",")
return map[string]string{
key: val,
}
}
type writeLogger struct {
prefix string
w io.Writer
filter string
}
func (l *writeLogger) Write(p []byte) (int, error) {
lines := bytes.SplitAfter(p, []byte("\n"))
for _, line := range lines {
s := string(line)
if l.filter != "" && strings.Contains(s, l.filter) || strings.TrimSpace(s) == "" {
continue
}
_, err := l.w.Write(p)
if err != nil {
fmt.Printf("%s %s: %v", l.prefix, s, err)
} else {
fmt.Printf("%s %s", l.prefix, s)
}
}
return len(p), nil
}
// NewWriteLogger returns a writer that behaves like w except
// that it logs (using fmt.Printf) each write to standard error,
// printing the prefix and the string data written.
func NewWriteLogger(prefix string, w io.Writer, filter string) io.Writer {
return &writeLogger{prefix, w, filter}
}
-128
View File
@@ -1,128 +0,0 @@
package controller
import (
"isp-config-service/cluster"
"isp-config-service/domain"
"isp-config-service/entity"
"isp-config-service/service"
"isp-config-service/store"
"isp-config-service/store/state"
)
var CommonConfig *commonConfig
type commonConfig struct {
rstore *store.Store
}
// GetConfigs godoc
// @Summary Метод получения объектов конфигурации по идентификаторам
// @Description Возвращает массив конфигураций по запрошенным идентификаторам (все, если массив пустой)
// @Tags Общие конфигурации
// @Accept json
// @Produce json
// @Success 200 {array} entity.CommonConfig
// @Router /common_config/get_configs [POST]
func (c *commonConfig) GetConfigs(identities []string) []entity.CommonConfig {
var response []entity.CommonConfig
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
if len(identities) > 0 {
response = state.CommonConfigs().GetByIds(identities)
} else {
response = state.CommonConfigs().GetAll()
}
})
return response
}
// CreateUpdateConfig godoc
// @Summary Метод обновления общей конфигурации
// @Description Если конфиг с таким id существует, то обновляет данные, если нет, то добавляет данные в базу
// В случае обновления рассылает все подключенным модулям актуальную конфигурацию
// @Tags Общие конфигурации
// @Accept json
// @Produce json
// @Param body body entity.CommonConfig true "объект для сохранения"
// @Success 200 {object} entity.CommonConfig
// @Failure 404 {object} structure.GrpcError "если конфигурация не найдена"
// @Failure 500 {object} structure.GrpcError
// @Router /common_config/create_update_config [POST]
func (c *commonConfig) CreateUpdateConfig(config entity.CommonConfig) (*entity.CommonConfig, error) {
var response entity.CommonConfig
now := state.GenerateDate()
config.CreatedAt = now
config.UpdatedAt = now
upsertConfig := cluster.UpsertCommonConfig{
Config: config,
}
if config.Id == "" {
upsertConfig.Config.Id = state.GenerateId()
upsertConfig.Create = true
}
command := cluster.PrepareUpsertCommonConfigCommand(upsertConfig)
err := PerformSyncApplyWithError(command, "UpsertCommonConfigCommand", &response)
if err != nil {
return nil, err
}
return &response, nil
}
// DeleteConfigs godoc
// @Summary Метод удаления объектов общей конфигурации по идентификаторам
// @Description Возвращает флаг удаления и набор связей с модулями и конфигурациями, в случае наличия связей deleted всегда false
// @Tags Общие конфигурации
// @Accept json
// @Produce json
// @Param body body domain.ConfigIdRequest true "id общей конфигурации"
// @Success 200 {object} domain.DeleteCommonConfigResponse
// @Failure 500 {object} structure.GrpcError
// @Router /common_config/delete_config [POST]
func (c *commonConfig) DeleteConfigs(req domain.ConfigIdRequest) (*domain.DeleteCommonConfigResponse, error) {
var response domain.DeleteCommonConfigResponse
command := cluster.PrepareDeleteCommonConfigsCommand(req.Id)
err := PerformSyncApplyWithError(command, "DeleteCommonConfigsCommand", &response)
if err != nil {
return nil, err
}
return &response, nil
}
// CompileConfigs godoc
// @Summary Метод компиляции итоговой конфигурации для модулей
// @Description Возвращает скомпилированный объект конфигурации
// @Tags Общие конфигурации
// @Accept json
// @Produce json
// @Param body body domain.CompileConfigsRequest true "перечисление идентификаторов общей конфигурации и исхдных конфиг"
// @Success 200 {object} domain.CompiledConfigResponse
// @Router /common_config/compile [POST]
func (c *commonConfig) CompileConfigs(req domain.CompileConfigsRequest) domain.CompiledConfigResponse {
var result map[string]interface{}
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
result = service.ConfigService.CompileConfig(req.Data, state, req.CommonConfigsIdList...)
})
return result
}
// GetLinks godoc
// @Summary Метод получения связей общей конфигурациями с конфигурацией модулей
// @Description Возвращает ассоциативный массив, ключами которого являются название модулей, а значения - название конфигурации модуля
// @Tags Общие конфигурации
// @Accept json
// @Produce json
// @Param body body domain.ConfigIdRequest true "id общей конфигурации"
// @Success 200 {object} domain.CommonConfigLinks
// @Router /common_config/get_links [POST]
func (c *commonConfig) GetLinks(req domain.ConfigIdRequest) domain.CommonConfigLinks {
var result domain.CommonConfigLinks
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
result = service.CommonConfigService.GetCommonConfigLinks(req.Id, state)
})
return result
}
func NewCommonConfig(rstore *store.Store) *commonConfig {
return &commonConfig{
rstore: rstore,
}
}
-133
View File
@@ -1,133 +0,0 @@
package controller
import (
"github.com/integration-system/isp-lib/utils"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"isp-config-service/cluster"
"isp-config-service/domain"
"isp-config-service/entity"
"isp-config-service/store"
"isp-config-service/store/state"
)
var Config *config
type config struct {
rstore *store.Store
}
// GetActiveConfigByModuleName godoc
// @Summary Метод получения объекта конфигурации по названию модуля
// @Description Возвращает активную конфиграцию по названию модуля
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.GetByModuleNameRequest true "название модуля"
// @Success 200 {object} entity.Config
// @Failure 404 {object} structure.GrpcError "если конфигурация не найдена"
// @Failure 500 {object} structure.GrpcError
// @Router /config/get_active_config_by_module_name [POST]
func (c *config) GetActiveConfigByModuleName(request domain.GetByModuleNameRequest) (*entity.Config, error) {
var response *entity.Config
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
module := state.Modules().GetByName(request.ModuleName)
if module != nil {
response = state.Configs().GetActiveByModuleId(module.Id)
}
})
if response == nil {
return nil, status.Error(codes.NotFound, utils.ValidationError)
}
return response, nil
}
// CreateUpdateConfig godoc
// @Summary Метод обновления конфигурации
// @Description Если конфиг с таким id существует, то обновляет данные, если нет, то добавляет данные в базу
// В случае обновления рассылает все подключенным модулям актуальную конфигурацию
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.CreateUpdateConfigRequest true "объект для сохранения"
// @Success 200 {object} domain.ConfigModuleInfo
// @Failure 404 {object} structure.GrpcError "если конфигурация не найдена"
// @Failure 500 {object} structure.GrpcError
// @Router /config/create_update_config [POST]
func (c *config) CreateUpdateConfig(config domain.CreateUpdateConfigRequest) (*domain.ConfigModuleInfo, error) {
var response domain.CreateUpdateConfigResponse
now := state.GenerateDate()
config.CreatedAt = now
config.UpdatedAt = now
upsertConfig := cluster.UpsertConfig{
Config: config.Config,
Unsafe: config.Unsafe,
}
if config.Id == "" {
upsertConfig.Config.Id = state.GenerateId()
upsertConfig.Create = true
}
command := cluster.PrepareUpsertConfigCommand(upsertConfig)
err := PerformSyncApplyWithError(command, "UpsertConfigCommand", &response)
if err != nil {
return nil, err
} else if response.Config != nil {
return response.Config, nil
} else {
return nil, utils.CreateValidationErrorDetails(codes.InvalidArgument, utils.ValidationError, response.ErrorDetails)
}
}
// MarkConfigAsActive godoc
// @Summary Метод активации конфигурации для модуля
// @Description Активирует указанную конфигурацию и деактивирует остальные, возвращает активированную конфигурацию
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.ConfigIdRequest true "id конфигурации для изменения"
// @Success 200 {object} entity.Config "активированная конфигурация"
// @Failure 404 {object} structure.GrpcError "если конфигурация не найдена"
// @Failure 500 {object} structure.GrpcError
// @Router /config/mark_config_as_active [POST]
func (c *config) MarkConfigAsActive(identity domain.ConfigIdRequest) (*entity.Config, error) {
var response entity.Config
command := cluster.PrepareActivateConfigCommand(identity.Id, state.GenerateDate())
err := PerformSyncApplyWithError(command, "ActivateConfigCommand", &response)
if err != nil {
return nil, err
}
return &response, nil
}
// DeleteConfigs godoc
// @Summary Метод удаления объектов конфигурации по идентификаторам
// @Description Возвращает количество удаленных модулей
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body []string true "массив идентификаторов конфигураций"
// @Success 200 {object} domain.DeleteResponse
// @Failure 400 {object} structure.GrpcError "если не указан массив идентификаторов"
// @Failure 500 {object} structure.GrpcError
// @Router /config/delete_config [POST]
func (c *config) DeleteConfigs(identities []string) (*domain.DeleteResponse, error) {
if len(identities) == 0 {
validationErrors := map[string]string{
"ids": "Required",
}
return nil, utils.CreateValidationErrorDetails(codes.InvalidArgument, utils.ValidationError, validationErrors)
}
var response domain.DeleteResponse
command := cluster.PrepareDeleteConfigsCommand(identities)
err := PerformSyncApply(command, "DeleteConfigsCommand", &response)
if err != nil {
return nil, err
}
return &response, nil
}
func NewConfig(rstore *store.Store) *config {
return &config{
rstore: rstore,
}
}
-66
View File
@@ -1,66 +0,0 @@
package controller
import (
"github.com/integration-system/isp-lib/utils"
log "github.com/integration-system/isp-log"
jsoniter "github.com/json-iterator/go"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"isp-config-service/cluster"
codes2 "isp-config-service/codes"
"isp-config-service/holder"
)
var json = jsoniter.ConfigFastest
func unknownError() error {
return status.Error(codes.Unknown, utils.ServiceError)
}
func PerformSyncApply(command []byte, commandName string, responsePtr interface{}) error {
applyLogResponse, err := holder.ClusterClient.SyncApply(command)
if err != nil {
log.Warnf(codes2.SyncApplyError, "apply %s: %v", commandName, err)
return unknownError()
}
if applyLogResponse != nil && applyLogResponse.ApplyError != "" {
log.WithMetadata(map[string]interface{}{
"result": string(applyLogResponse.Result),
"applyError": applyLogResponse.ApplyError,
"commandName": commandName,
}).Warnf(codes2.SyncApplyError, "apply command")
return unknownError()
}
err = json.Unmarshal(applyLogResponse.Result, responsePtr)
if err != nil {
return unknownError()
}
return nil
}
func PerformSyncApplyWithError(command []byte, commandName string, responsePtr interface{}) error {
applyLogResponse, err := holder.ClusterClient.SyncApply(command)
if err != nil {
log.Warnf(codes2.SyncApplyError, "apply %s: %v", commandName, err)
return unknownError()
}
if applyLogResponse != nil && applyLogResponse.ApplyError != "" {
log.WithMetadata(map[string]interface{}{
"result": string(applyLogResponse.Result),
"applyError": applyLogResponse.ApplyError,
"commandName": commandName,
}).Warnf(codes2.SyncApplyError, "apply command")
return unknownError()
}
clusterResp := cluster.ResponseWithError{
Response: responsePtr,
}
err = json.Unmarshal(applyLogResponse.Result, &clusterResp)
if err != nil {
return unknownError()
}
if clusterResp.Error != "" {
return status.Error(clusterResp.ErrorCode, clusterResp.Error)
}
return nil
}
-68
View File
@@ -1,68 +0,0 @@
package controller
import (
"isp-config-service/cluster"
"isp-config-service/domain"
"isp-config-service/service"
"isp-config-service/store"
"isp-config-service/store/state"
"github.com/integration-system/isp-lib/utils"
"google.golang.org/grpc/codes"
)
var Module *module
type module struct {
rstore *store.Store
}
// GetModulesAggregatedInfo godoc
// @Summary Метод получения полной информации о состоянии модуля
// @Description Возвращает полное состояние всех модулей в кластере (конфигурация, схема конфигурации, подключенные экземпляры)
// @Tags Модули
// @Accept json
// @Produce json
// @Success 200 {array} domain.ModuleInfo
// @Failure 500 {object} structure.GrpcError
// @Router /module/get_modules_info [POST]
func (c *module) GetModulesAggregatedInfo() ([]domain.ModuleInfo, error) {
var response []domain.ModuleInfo
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
response = service.ModuleRegistryService.GetAggregatedModuleInfo(state)
})
return response, nil
}
// DeleteModules godoc
// @Summary Метод удаления объектов модулей по идентификаторам
// @Description Возвращает количество удаленных модулей
// @Tags Модули
// @Accept json
// @Produce json
// @Param body body []string true "массив идентификаторов модулей"
// @Success 200 {object} domain.DeleteResponse
// @Failure 500 {object} structure.GrpcError
// @Router /module/delete_module [POST]
func (*module) DeleteModules(identities []string) (*domain.DeleteResponse, error) {
if len(identities) == 0 {
validationErrors := map[string]string{
"ids": "Required",
}
return nil, utils.CreateValidationErrorDetails(codes.InvalidArgument, utils.ValidationError, validationErrors)
}
var deleteResponse domain.DeleteResponse
command := cluster.PrepareDeleteModulesCommand(identities)
err := PerformSyncApply(command, "DeleteCommonConfigsCommand", &deleteResponse)
if err != nil {
return nil, err
}
return &deleteResponse, err
}
func NewModule(rstore *store.Store) *module {
return &module{
rstore: rstore,
}
}
-37
View File
@@ -1,37 +0,0 @@
package controller
import (
"github.com/integration-system/isp-lib/structure"
"isp-config-service/store"
"isp-config-service/store/state"
)
var (
Routes *routes
)
type routes struct {
rstore *store.Store
}
// GetRoutes godoc
// @Summary Метод получения маршрутов
// @Description Возвращает все доступные модули
// @Tags Роуты
// @Accept json
// @Produce json
// @Success 200 {array} structure.BackendDeclaration
// @Router /routing/get_routes [POST]
func (c *routes) GetRoutes() ([]structure.BackendDeclaration, error) {
var response structure.RoutingConfig
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
response = state.Mesh().GetRoutes()
})
return response, nil
}
func NewRoutes(rstore *store.Store) *routes {
return &routes{
rstore: rstore,
}
}
-44
View File
@@ -1,44 +0,0 @@
package controller
import (
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"isp-config-service/domain"
"isp-config-service/entity"
"isp-config-service/store"
"isp-config-service/store/state"
)
var Schema *schema
type schema struct {
rstore *store.Store
}
// GetByModuleId godoc
// @Summary Метод получения схемы конфигурации модуля
// @Description Возвращает текущую json схему конфигурации модуля
// @Tags Схема
// @Accept json
// @Produce json
// @Param body body domain.GetByModuleIdRequest true "идентификатор модуля"
// @Success 200 {object} entity.ConfigSchema
// @Failure 404 {object} structure.GrpcError "если схема для модуля не найдена"
// @Failure 500 {object} structure.GrpcError
// @Router /schema/get_by_module_id [POST]
func (c *schema) GetByModuleId(request domain.GetByModuleIdRequest) (*entity.ConfigSchema, error) {
var result []entity.ConfigSchema
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
result = state.Schemas().GetByModuleIds([]string{request.ModuleId})
})
if len(result) == 0 {
return nil, status.Errorf(codes.NotFound, "schema with moduleId %s not found", request.ModuleId)
}
return &result[0], nil
}
func NewSchema(rstore *store.Store) *schema {
return &schema{
rstore: rstore,
}
}
+169
View File
@@ -0,0 +1,169 @@
package controllers
import (
"fmt"
st "isp-config-service/entity"
"isp-config-service/model"
"isp-config-service/socket"
"github.com/integration-system/isp-lib/utils"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"isp-config-service/domain"
)
// GetConfigs godoc
// @Tags Конфигурация
// @Summary Метод получения объектов конфигурации по идентификаторам
// @Description Возвращает массив конфиграций по запрошенным идентификаторам (все, если массив пустой)
// @Accept json
// @Produce json
// @Param body body []integer false "Массив идентификаторов конфигураций"
// @Success 200 {array} entity.Config
// @Failure 500 {object} structure.GrpcError
// @Router /config/get_configs [POST]
func GetConfigs(identities []int64) ([]st.Config, error) {
configs, err := model.ConfigRep.GetConfigs(identities)
if err != nil {
return nil, createUnknownError(err)
}
return configs, nil
}
// GetConfigByInstanceUUIDAndModuleName godoc
// @Tags Конфигурация
// @Summary Метод получени объекта конфигурации по названию модуля
// @Description Возвращает конфиграцию по названию модуля и идентификатору инстанса
// @Accept json
// @Produce json
// @Param body body entity.ModuleInstanceIdentity true "название модуля и id кластера"
// @Success 200 {object} entity.Config
// @Failure 404 {object} structure.GrpcError "если конфигурация не найдена"
// @Failure 500 {object} structure.GrpcError
// @Router /config/get_config_by_instance_uuid_and_module_name [POST]
func GetConfigByInstanceUUIDAndModuleName(request st.ModuleInstanceIdentity) (*st.Config, error) {
config, err := model.ConfigRep.GetConfigByInstanceUUIDAndModuleName(request.Uuid, request.Name)
if err != nil {
return nil, createUnknownError(err)
}
if config == nil {
return nil, status.Error(codes.NotFound, utils.ValidationError)
}
return config, nil
}
// CreateUpdateConfig godoc
// @Tags Конфигурация
// @Summary Метод обновления конфигурации
// @Description Если конфиг с таким id существует, то обновляет данные, если нет, то добавляет данные в базу
// В случае обновления рассылает все подключенным модулям актуальную конфигурацию
// @Accept json
// @Produce json
// @Param body body entity.Config true "объект для сохранения"
// @Success 200 {object} entity.Config
// @Failure 404 {object} structure.GrpcError "если конфигурация не найдена"
// @Failure 500 {object} structure.GrpcError
// @Router /config/create_update_config [POST]
func CreateUpdateConfig(config st.Config) (*st.Config, error) {
var err error
var cfg *st.Config
if config.Id == 0 {
cfg, err = model.ConfigRep.CreateConfig(&config)
if err != nil {
return nil, err
}
} else {
configExists, err := model.ConfigRep.GetConfigById(config.Id)
if err != nil {
return nil, err
}
if configExists == nil {
validationErrors := map[string]string{
"id": fmt.Sprintf("Entity with id: %d not found", config.Id),
}
return nil, utils.CreateValidationErrorDetails(codes.NotFound, utils.ValidationError, validationErrors)
}
cfg, err = model.ConfigRep.UpdateConfig(&config)
if err != nil {
return nil, err
}
}
if cfg.Active {
moduleInstanceIdentity, err := model.ConfigRep.GetModuleNameAndInstanceUUIDByConfigId(cfg.Id)
if err != nil {
return nil, createUnknownError(err)
}
socket.SendNewConfig(moduleInstanceIdentity.Uuid, moduleInstanceIdentity.Name, cfg)
}
return cfg, nil
}
// UpdateActiveConfigByInstanceUUIDAndModuleName godoc
// @Tags Конфигурация
// @Summary Метод обновления конфигурации по названию модуля
// @Description Обновляет объект конфиграции для модуля, рассылает подключенным модулям обновленную конфигурацию
// @Accept json
// @Produce json
// @Param body body domain.ConfigInstanceModuleName true "объект для сохранения"
// @Success 200 {object} entity.Config "объект для сохранения"
// @Failure 404 {object} structure.GrpcError "если конфигурация не найдена"
// @Failure 500 {object} structure.GrpcError
// @Router /config/update_active_config_by_instance_uuid_and_module_name [POST]
func UpdateActiveConfigByInstanceUUIDAndModuleName(configReq domain.ConfigInstanceModuleName) (*st.Config, error) {
config, err := model.ConfigRep.GetConfigByInstanceUUIDAndModuleName(configReq.InstanceUuid, configReq.ModuleName)
if err != nil || config == nil {
validationErrors := map[string]string{
"id": fmt.Sprintf("Active config for module: %s and instance uuid: %s not found",
configReq.ModuleName, configReq.InstanceUuid),
}
return nil, utils.CreateValidationErrorDetails(codes.NotFound, utils.ValidationError, validationErrors)
}
config.Data = configReq.ConfigData
return CreateUpdateConfig(*config)
}
func MarkConfigAsActive(identity domain.LongIdentitiesRequest) (*st.Config, error) {
configExists, err := model.ConfigRep.GetConfigById(identity.Id)
if err != nil {
return nil, createUnknownError(err)
}
if configExists == nil {
validationErrors := map[string]string{
"id": fmt.Sprintf("Entity with id: %d not found", identity.Id),
}
return nil, utils.CreateValidationErrorDetails(codes.NotFound, utils.ValidationError, validationErrors)
}
configExists.Active = true
configExists, err = model.ConfigRep.UpdateConfig(configExists)
if err != nil {
return nil, err
}
if configExists.Active {
moduleInstanceIdentity, err := model.ConfigRep.GetModuleNameAndInstanceUUIDByConfigId(configExists.Id)
if err != nil {
return nil, createUnknownError(err)
}
socket.SendNewConfig(moduleInstanceIdentity.Uuid, moduleInstanceIdentity.Name, configExists)
}
return configExists, nil
}
func DeleteConfig(identities []int64) (*domain.DeleteResponse, error) {
if len(identities) == 0 {
validationErrors := map[string]string{
"ids": "Required",
}
return nil, utils.CreateValidationErrorDetails(codes.InvalidArgument, utils.ValidationError, validationErrors)
}
count, err := model.ConfigRep.DeleteConfig(identities)
if err != nil {
return nil, createUnknownError(err)
}
return &domain.DeleteResponse{Deleted: count}, err
}
+73
View File
@@ -0,0 +1,73 @@
package controllers
import (
"fmt"
st "isp-config-service/entity"
"isp-config-service/model"
"isp-config-service/domain"
"github.com/integration-system/isp-lib/logger"
"github.com/integration-system/isp-lib/utils"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func GetInstances(identities []int32) ([]st.Instance, error) {
instances, err := model.InstanceRep.GetInstances(identities)
if err != nil {
return nil, createUnknownError(err)
}
return instances, err
}
func CreateUpdateInstance(instance st.Instance) (*st.Instance, error) {
if instance.Id == 0 {
moduleExists, err := model.InstanceRep.GetInstanceByUuid(instance.Uuid)
if err != nil {
return nil, createUnknownError(err)
}
if moduleExists.Id != 0 {
validationErrors := map[string]string{
"name": fmt.Sprintf("Entity with uuid: %s already exists", instance.Name),
}
return nil, utils.CreateValidationErrorDetails(codes.AlreadyExists, utils.ValidationError, validationErrors)
}
instance, err = model.InstanceRep.CreateInstance(instance)
} else {
instanceExists, err := model.InstanceRep.GetInstanceById(instance.Id)
if err != nil {
return nil, createUnknownError(err)
}
if instanceExists.Id == 0 {
validationErrors := map[string]string{
"id": fmt.Sprintf("Entity with id: %d not found", instance.Id),
}
return nil, utils.CreateValidationErrorDetails(codes.NotFound, utils.ValidationError, validationErrors)
}
instance, err = model.InstanceRep.UpdateInstance(instance)
instance.CreatedAt = instanceExists.CreatedAt
}
return &instance, nil
}
func DeleteInstance(identities []int32) (*domain.DeleteResponse, error) {
if len(identities) == 0 {
validationErrors := map[string]string{
"ids": "Required",
}
return nil, utils.CreateValidationErrorDetails(codes.InvalidArgument, utils.ValidationError, validationErrors)
}
count, err := model.InstanceRep.DeleteInstance(identities)
if err != nil {
return nil, createUnknownError(err)
}
return &domain.DeleteResponse{Deleted: count}, err
}
func createUnknownError(err error) error {
logger.Error(err)
return status.Error(codes.Unknown, utils.ServiceError)
}
+16
View File
@@ -0,0 +1,16 @@
package controllers
/*var HandlerSwagger = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
values, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("Method not received"))
}
method := values.Get("method")
if method == "" {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("Method not received"))
}
proxyRequestHandle(w, r, method)
})
*/
+133
View File
@@ -0,0 +1,133 @@
package controllers
import (
"encoding/json"
"fmt"
st "isp-config-service/entity"
"isp-config-service/model"
"isp-config-service/module"
"isp-config-service/socket"
"isp-config-service/domain"
"github.com/integration-system/isp-lib/structure"
"github.com/integration-system/isp-lib/utils"
"google.golang.org/grpc/codes"
)
// GetModules godoc
// @Tags Модули
// @Summary Метод получени объектов модулей по идентификаторам
// @Description Возвращает массив модулей по запрошенным идентификаторам (все, если массив пустой)
// @Accept json
// @Produce json
// @Param body body []integer false "массив идентификаторов модулей"
// @Success 200 {array} entity.Module
// @Failure 500 {object} structure.GrpcError
// @Router /config/get_modules [POST]
func GetModules(identities []int32) ([]st.Module, error) {
modules, err := model.ModulesRep.GetModules(identities)
if err != nil {
return nil, createUnknownError(err)
}
return modules, nil
}
// GetModulesAggregatedInfo godoc
// @Tags Модули
// @Summary Метод получения полной информации о состоянии модуля
// @Description Возвращает полное состояние всех модулей в кластере (конфигурация, схема конфигурации, подключенные экземпляры)
// @Accept json
// @Produce json
// @Param x-instance-identity header string true "идентификатор кластера"
// @Success 200 {array} domain.ModuleInfo
// @Failure 500 {object} structure.GrpcError
// @Router /config/get_modules_info [POST]
func GetModulesAggregatedInfo(i structure.Isolation) ([]*domain.ModuleInfo, error) {
instanceId, err := i.GetInstanceId()
if err != nil {
return nil, err
}
return module.GetAggregatedModuleInfo(instanceId)
}
func GetActiveModules() ([]st.Module, error) {
modules, err := model.ModulesRep.GetActiveModules()
if err != nil {
return nil, createUnknownError(err)
}
return modules, nil
}
func GetConnectedModules() (map[string]interface{}, error) {
modules := socket.GetRoomsCount()
bytes, err := json.Marshal(modules)
if err != nil {
return nil, createUnknownError(err)
}
var response map[string]interface{}
err = json.Unmarshal(bytes, &response)
if err != nil {
return nil, createUnknownError(err)
}
return response, nil
}
func CreateUpdateModule(module st.Module) (*st.Module, error) {
if module.Id == 0 {
instanceExists, err := model.InstanceRep.GetInstanceById(module.InstanceId)
if err != nil {
return nil, createUnknownError(err)
}
if instanceExists.Id == 0 {
validationErrors := map[string]string{
"instanceId": fmt.Sprintf("Entity with instanceId: %d not found", module.InstanceId),
}
return nil, utils.CreateValidationErrorDetails(codes.NotFound, utils.ValidationError, validationErrors)
}
moduleExists, err := model.ModulesRep.GetModuleByInstanceIdAndName(module.InstanceId, module.Name)
if err != nil {
return nil, createUnknownError(err)
}
if moduleExists.Id != 0 {
validationErrors := map[string]string{
"name": fmt.Sprintf("Entity with name: %s already exists", module.Name),
}
return nil, utils.CreateValidationErrorDetails(codes.AlreadyExists, utils.ValidationError, validationErrors)
}
module, err = model.ModulesRep.CreateModule(module)
} else {
moduleExists, err := model.ModulesRep.GetModuleById(module.Id)
if err != nil {
return nil, createUnknownError(err)
}
if moduleExists.Id == 0 {
validationErrors := map[string]string{
"id": fmt.Sprintf("Entity with id: %d not found", module.Id),
}
return nil, utils.CreateValidationErrorDetails(codes.NotFound, utils.ValidationError, validationErrors)
}
module, err = model.ModulesRep.UpdateModule(module)
module.CreatedAt = moduleExists.CreatedAt
module.Active = moduleExists.Active
}
return &module, nil
}
func DeleteModule(identities []int32) (*domain.DeleteResponse, error) {
if len(identities) == 0 {
validationErrors := map[string]string{
"ids": "Required",
}
return nil, utils.CreateValidationErrorDetails(codes.InvalidArgument, utils.ValidationError, validationErrors)
}
count, err := model.ModulesRep.DeleteModule(identities)
if err != nil {
return nil, createUnknownError(err)
}
return &domain.DeleteResponse{Deleted: count}, err
}
+20
View File
@@ -0,0 +1,20 @@
package controllers
import (
"encoding/json"
"isp-config-service/socket"
)
func GetRoutes() (map[string]interface{}, error) {
bytes, err := json.Marshal(socket.GetRoutes().Routes)
if err != nil {
return nil, createUnknownError(err)
}
var response map[string]interface{}
err = json.Unmarshal(bytes, &response)
if err != nil {
return nil, createUnknownError(err)
}
return response, nil
}
+34
View File
@@ -0,0 +1,34 @@
package controllers
import (
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"isp-config-service/domain"
"isp-config-service/entity"
"isp-config-service/model"
)
var Schema = schema{}
type schema struct{}
// GetModulesAggregatedInfo godoc
// @Tags Схема
// @Summary Метод схемы конфигурации модуля
// @Description Возвращает текущую json схему конфигурации модуля
// @Accept json
// @Produce json
// @Param body body domain.GetByModuleIdRequest true "идентификатор модуля"
// @Success 200 {array} entity.ConfigSchema
// @Failure 404 {object} structure.GrpcError "если схема для модуля не найдена"
// @Failure 500 {object} structure.GrpcError
// @Router /config/get_modules_info [POST]
func (schema) GetByModuleId(request domain.GetByModuleIdRequest) (*entity.ConfigSchema, error) {
if response, err := model.SchemaRep.GetSchemaByModuleId(request.ModuleId); err != nil {
return nil, err
} else if response == nil {
return nil, status.Errorf(codes.NotFound, "schema with moduleId %d not found", request.ModuleId)
} else {
return response, nil
}
}
-988
View File
@@ -1,988 +0,0 @@
basePath: /api/config
definitions:
domain.CommonConfigLinks:
additionalProperties:
items: {}
type: array
type: object
domain.CompileConfigsRequest:
properties:
commonConfigsIdList:
items:
type: string
type: array
data:
type: object
type: object
domain.CompiledConfigResponse:
additionalProperties:
type: object
type: object
domain.ConfigIdRequest:
properties:
id:
type: string
required:
- id
type: object
domain.ConfigModuleInfo:
properties:
active:
type: boolean
commonConfigs:
items:
type: string
type: array
createdAt:
type: string
data:
$ref: '#/definitions/entity.ConfigData'
type: object
description:
type: string
id:
type: string
moduleId:
type: string
name:
type: string
updatedAt:
type: string
valid:
type: boolean
version:
type: integer
required:
- moduleId
- name
type: object
domain.Connection:
properties:
address:
$ref: '#/definitions/structure.AddressConfiguration'
type: object
endpoints:
items:
$ref: '#/definitions/structure.EndpointConfig'
type: array
establishedAt:
type: string
libVersion:
type: string
version:
type: string
type: object
domain.CreateUpdateConfigRequest:
properties:
active:
type: boolean
commonConfigs:
items:
type: string
type: array
createdAt:
type: string
data:
$ref: '#/definitions/entity.ConfigData'
type: object
description:
type: string
id:
type: string
moduleId:
type: string
name:
type: string
unsafe:
type: boolean
updatedAt:
type: string
version:
type: integer
required:
- moduleId
- name
type: object
domain.DeleteCommonConfigResponse:
properties:
deleted:
type: boolean
links:
$ref: '#/definitions/domain.CommonConfigLinks'
type: object
type: object
domain.DeleteResponse:
properties:
deleted:
type: integer
type: object
domain.GetByModuleIdRequest:
properties:
moduleId:
type: string
required:
- moduleId
type: object
domain.GetByModuleNameRequest:
properties:
moduleName:
type: string
required:
- moduleName
type: object
domain.ModuleInfo:
properties:
active:
type: boolean
configSchema:
$ref: '#/definitions/schema.Schema'
type: object
configs:
items:
$ref: '#/definitions/domain.ConfigModuleInfo'
type: array
createdAt:
type: string
id:
type: string
lastConnectedAt:
type: string
lastDisconnectedAt:
type: string
name:
type: string
status:
items:
$ref: '#/definitions/domain.Connection'
type: array
type: object
entity.CommonConfig:
properties:
createdAt:
type: string
data:
$ref: '#/definitions/entity.ConfigData'
type: object
description:
type: string
id:
type: string
name:
type: string
updatedAt:
type: string
required:
- name
type: object
entity.Config:
properties:
active:
type: boolean
commonConfigs:
items:
type: string
type: array
createdAt:
type: string
data:
$ref: '#/definitions/entity.ConfigData'
type: object
description:
type: string
id:
type: string
moduleId:
type: string
name:
type: string
updatedAt:
type: string
version:
type: integer
required:
- moduleId
- name
type: object
entity.ConfigData:
additionalProperties:
type: object
type: object
entity.ConfigSchema:
properties:
createdAt:
type: string
id:
type: string
moduleId:
type: string
schema:
$ref: '#/definitions/schema.Schema'
type: object
updatedAt:
type: string
version:
type: string
type: object
jsonschema.Definitions:
additionalProperties: {}
type: object
jsonschema.Schema:
properties:
$ref:
description: section 7
type: string
$schema:
description: RFC draft-wright-json-schema-00
type: string
additionalItems:
description: section 5.9
type: integer
additionalProperties:
description: section 5.18
type: string
allOf:
description: section 5.22
items:
$ref: '#/definitions/jsonschema.Type'
type: array
anyOf:
description: section 5.23
items:
$ref: '#/definitions/jsonschema.Type'
type: array
binaryEncoding:
description: section 4.3
type: string
default:
description: section 6.2
type: object
definitions:
$ref: '#/definitions/jsonschema.Definitions'
type: object
dependencies:
description: section 5.19
type: object
description:
description: section 6.1
type: string
enum:
description: section 5.20
items:
type: object
type: array
exclusiveMaximum:
description: section 5.3
type: boolean
exclusiveMinimum:
description: section 5.5
type: boolean
format:
description: section 7
type: string
items:
description: section 5.9
type: integer
maxItems:
description: section 5.10
type: integer
maxLength:
description: section 5.6
type: integer
maxProperties:
description: section 5.13
type: integer
maximum:
description: section 5.2
type: integer
media:
description: RFC draft-wright-json-schema-hyperschema-00, section 4
type: integer
minItems:
description: section 5.11
type: integer
minLength:
description: section 5.7
type: integer
minProperties:
description: section 5.14
type: integer
minimum:
description: section 5.4
type: integer
multipleOf:
description: RFC draft-wright-json-schema-validation-00, section 5
type: integer
not:
description: section 5.25
type: integer
oneOf:
description: section 5.24
items:
$ref: '#/definitions/jsonschema.Type'
type: array
pattern:
description: section 5.8
type: string
patternProperties:
description: section 5.17
type: object
properties:
description: section 5.16
type: object
required:
description: section 5.15
items:
type: string
type: array
title:
description: RFC draft-wright-json-schema-validation-00, section 6, 7
type: string
type:
description: section 5.21
type: string
uniqueItems:
description: section 5.12
type: boolean
type: object
jsonschema.Type:
properties:
$ref:
description: section 7
type: string
$schema:
description: RFC draft-wright-json-schema-00
type: string
additionalItems:
description: section 5.9
type: integer
additionalProperties:
description: section 5.18
type: string
allOf:
description: section 5.22
items:
$ref: '#/definitions/jsonschema.Type'
type: array
anyOf:
description: section 5.23
items:
$ref: '#/definitions/jsonschema.Type'
type: array
binaryEncoding:
description: section 4.3
type: string
default:
description: section 6.2
type: object
definitions:
$ref: '#/definitions/jsonschema.Definitions'
description: section 5.26
type: object
dependencies:
description: section 5.19
type: object
description:
description: section 6.1
type: string
enum:
description: section 5.20
items:
type: object
type: array
exclusiveMaximum:
description: section 5.3
type: boolean
exclusiveMinimum:
description: section 5.5
type: boolean
format:
description: section 7
type: string
items:
description: section 5.9
type: integer
maxItems:
description: section 5.10
type: integer
maxLength:
description: section 5.6
type: integer
maxProperties:
description: section 5.13
type: integer
maximum:
description: section 5.2
type: integer
media:
description: RFC draft-wright-json-schema-hyperschema-00, section 4
type: integer
minItems:
description: section 5.11
type: integer
minLength:
description: section 5.7
type: integer
minProperties:
description: section 5.14
type: integer
minimum:
description: section 5.4
type: integer
multipleOf:
description: RFC draft-wright-json-schema-validation-00, section 5
type: integer
not:
description: section 5.25
type: integer
oneOf:
description: section 5.24
items:
$ref: '#/definitions/jsonschema.Type'
type: array
pattern:
description: section 5.8
type: string
patternProperties:
description: section 5.17
type: object
properties:
description: section 5.16
type: object
required:
description: section 5.15
items:
type: string
type: array
title:
description: RFC draft-wright-json-schema-validation-00, section 6, 7
type: string
type:
description: section 5.21
type: string
uniqueItems:
description: section 5.12
type: boolean
type: object
schema.Schema:
properties:
$ref:
description: section 7
type: string
$schema:
description: RFC draft-wright-json-schema-00
type: string
additionalItems:
description: section 5.9
type: integer
additionalProperties:
description: section 5.18
type: string
allOf:
description: section 5.22
items:
$ref: '#/definitions/jsonschema.Type'
type: array
anyOf:
description: section 5.23
items:
$ref: '#/definitions/jsonschema.Type'
type: array
binaryEncoding:
description: section 4.3
type: string
default:
description: section 6.2
type: object
definitions:
$ref: '#/definitions/jsonschema.Definitions'
type: object
dependencies:
description: section 5.19
type: object
description:
description: section 6.1
type: string
enum:
description: section 5.20
items:
type: object
type: array
exclusiveMaximum:
description: section 5.3
type: boolean
exclusiveMinimum:
description: section 5.5
type: boolean
format:
description: section 7
type: string
items:
description: section 5.9
type: integer
maxItems:
description: section 5.10
type: integer
maxLength:
description: section 5.6
type: integer
maxProperties:
description: section 5.13
type: integer
maximum:
description: section 5.2
type: integer
media:
description: RFC draft-wright-json-schema-hyperschema-00, section 4
type: integer
minItems:
description: section 5.11
type: integer
minLength:
description: section 5.7
type: integer
minProperties:
description: section 5.14
type: integer
minimum:
description: section 5.4
type: integer
multipleOf:
description: RFC draft-wright-json-schema-validation-00, section 5
type: integer
not:
description: section 5.25
type: integer
oneOf:
description: section 5.24
items:
$ref: '#/definitions/jsonschema.Type'
type: array
pattern:
description: section 5.8
type: string
patternProperties:
description: section 5.17
type: object
properties:
description: section 5.16
type: object
required:
description: section 5.15
items:
type: string
type: array
title:
description: RFC draft-wright-json-schema-validation-00, section 6, 7
type: string
type:
description: section 5.21
type: string
uniqueItems:
description: section 5.12
type: boolean
type: object
structure.AddressConfiguration:
properties:
ip:
type: string
port:
type: string
type: object
structure.BackendDeclaration:
properties:
address:
$ref: '#/definitions/structure.AddressConfiguration'
type: object
endpoints:
items:
$ref: '#/definitions/structure.EndpointConfig'
type: array
libVersion:
type: string
moduleName:
type: string
version:
type: string
type: object
structure.EndpointConfig:
properties:
ignoreOnRouter:
type: boolean
inner:
type: boolean
path:
type: string
required:
- path
type: object
structure.GrpcError:
properties:
details:
items:
type: object
type: array
errorCode:
type: string
errorMessage:
type: string
type: object
host: localhost:9003
info:
contact: {}
description: Сервис управления конфигурацией модулей ISP кластера
license:
name: GNU GPL v3.0
title: ISP configuration service
version: 2.0.0
paths:
/common_config/compile:
post:
consumes:
- application/json
description: Возвращает скомпилированный объект конфигурации
parameters:
- description: перечисление идентификаторов общей конфигурации и исхдных конфиг
in: body
name: body
required: true
schema:
$ref: '#/definitions/domain.CompileConfigsRequest'
type: object
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/domain.CompiledConfigResponse'
summary: Метод компиляции итоговой конфигурации для модулей
tags:
- Общие конфигурации
/common_config/create_update_config:
post:
consumes:
- application/json
description: Если конфиг с таким id существует, то обновляет данные, если нет,
то добавляет данные в базу
parameters:
- description: объект для сохранения
in: body
name: body
required: true
schema:
$ref: '#/definitions/entity.CommonConfig'
type: object
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/entity.CommonConfig'
"404":
description: если конфигурация не найдена
schema:
$ref: '#/definitions/structure.GrpcError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/structure.GrpcError'
summary: Метод обновления общей конфигурации
tags:
- Общие конфигурации
/common_config/delete_config:
post:
consumes:
- application/json
description: Возвращает флаг удаления и набор связей с модулями и конфигурациями,
в случае наличия связей deleted всегда false
parameters:
- description: id общей конфигурации
in: body
name: body
required: true
schema:
$ref: '#/definitions/domain.ConfigIdRequest'
type: object
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/domain.DeleteCommonConfigResponse'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/structure.GrpcError'
summary: Метод удаления объектов общей конфигурации по идентификаторам
tags:
- Общие конфигурации
/common_config/get_configs:
post:
consumes:
- application/json
description: Возвращает массив конфигураций по запрошенным идентификаторам (все,
если массив пустой)
produces:
- application/json
responses:
"200":
description: OK
schema:
items:
$ref: '#/definitions/entity.CommonConfig'
type: array
summary: Метод получения объектов конфигурации по идентификаторам
tags:
- Общие конфигурации
/common_config/get_links:
post:
consumes:
- application/json
description: Возвращает ассоциативный массив, ключами которого являются название
модулей, а значения - название конфигурации модуля
parameters:
- description: id общей конфигурации
in: body
name: body
required: true
schema:
$ref: '#/definitions/domain.ConfigIdRequest'
type: object
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/domain.CommonConfigLinks'
summary: Метод получения связей общей конфигурациями с конфигурацией модулей
tags:
- Общие конфигурации
/config/create_update_config:
post:
consumes:
- application/json
description: Если конфиг с таким id существует, то обновляет данные, если нет,
то добавляет данные в базу
parameters:
- description: объект для сохранения
in: body
name: body
required: true
schema:
$ref: '#/definitions/domain.CreateUpdateConfigRequest'
type: object
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/domain.ConfigModuleInfo'
"404":
description: если конфигурация не найдена
schema:
$ref: '#/definitions/structure.GrpcError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/structure.GrpcError'
summary: Метод обновления конфигурации
tags:
- Конфигурация
/config/delete_config:
post:
consumes:
- application/json
description: Возвращает количество удаленных модулей
parameters:
- description: массив идентификаторов конфигураций
in: body
name: body
required: true
schema:
items:
type: string
type: array
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/domain.DeleteResponse'
"400":
description: если не указан массив идентификаторов
schema:
$ref: '#/definitions/structure.GrpcError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/structure.GrpcError'
summary: Метод удаления объектов конфигурации по идентификаторам
tags:
- Конфигурация
/config/get_active_config_by_module_name:
post:
consumes:
- application/json
description: Возвращает активную конфиграцию по названию модуля
parameters:
- description: название модуля
in: body
name: body
required: true
schema:
$ref: '#/definitions/domain.GetByModuleNameRequest'
type: object
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/entity.Config'
"404":
description: если конфигурация не найдена
schema:
$ref: '#/definitions/structure.GrpcError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/structure.GrpcError'
summary: Метод получения объекта конфигурации по названию модуля
tags:
- Конфигурация
/config/mark_config_as_active:
post:
consumes:
- application/json
description: Активирует указанную конфигурацию и деактивирует остальные, возвращает
активированную конфигурацию
parameters:
- description: id конфигурации для изменения
in: body
name: body
required: true
schema:
$ref: '#/definitions/domain.ConfigIdRequest'
type: object
produces:
- application/json
responses:
"200":
description: активированная конфигурация
schema:
$ref: '#/definitions/entity.Config'
"404":
description: если конфигурация не найдена
schema:
$ref: '#/definitions/structure.GrpcError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/structure.GrpcError'
summary: Метод активации конфигурации для модуля
tags:
- Конфигурация
/module/delete_module:
post:
consumes:
- application/json
description: Возвращает количество удаленных модулей
parameters:
- description: массив идентификаторов модулей
in: body
name: body
required: true
schema:
items:
type: string
type: array
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/domain.DeleteResponse'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/structure.GrpcError'
summary: Метод удаления объектов модулей по идентификаторам
tags:
- Модули
/module/get_modules_info:
post:
consumes:
- application/json
description: Возвращает полное состояние всех модулей в кластере (конфигурация,
схема конфигурации, подключенные экземпляры)
produces:
- application/json
responses:
"200":
description: OK
schema:
items:
$ref: '#/definitions/domain.ModuleInfo'
type: array
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/structure.GrpcError'
summary: Метод получения полной информации о состоянии модуля
tags:
- Модули
/routing/get_routes:
post:
consumes:
- application/json
description: Возвращает все доступные модули
produces:
- application/json
responses:
"200":
description: OK
schema:
items:
$ref: '#/definitions/structure.BackendDeclaration'
type: array
summary: Метод получения маршрутов
tags:
- Роуты
/schema/get_by_module_id:
post:
consumes:
- application/json
description: Возвращает текущую json схему конфигурации модуля
parameters:
- description: идентификатор модуля
in: body
name: body
required: true
schema:
$ref: '#/definitions/domain.GetByModuleIdRequest'
type: object
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/entity.ConfigSchema'
"404":
description: если схема для модуля не найдена
schema:
$ref: '#/definitions/structure.GrpcError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/structure.GrpcError'
summary: Метод получения схемы конфигурации модуля
tags:
- Схема
swagger: "2.0"
+11 -17
View File
@@ -1,25 +1,19 @@
package domain
import "isp-config-service/entity"
type ConfigIdRequest struct {
Id string `json:"id" valid:"required~Required"`
type IdentitiesRequest struct {
Ids []int32 `json:"ids" valid:"required~Required"`
}
type CompileConfigsRequest struct {
Data map[string]interface{}
CommonConfigsIdList []string
type LongIdentitiesRequest struct {
Id int64 `json:"id" valid:"required~Required"`
}
type ConfigInstanceModuleName struct {
ModuleName string `valid:"required~Required"`
InstanceUuid string `valid:"required~Required"`
ConfigData map[string]interface{} `valid:"required~Required"`
}
type GetByModuleIdRequest struct {
ModuleId string `valid:"required~Required"`
}
type GetByModuleNameRequest struct {
ModuleName string `valid:"required~Required"`
}
type CreateUpdateConfigRequest struct {
entity.Config
Unsafe bool
ModuleId int32 `valid:"required~Required"`
}
+14 -31
View File
@@ -1,28 +1,18 @@
package domain
import (
"time"
"isp-config-service/entity"
"github.com/integration-system/isp-lib/config/schema"
"github.com/integration-system/isp-lib/structure"
"isp-config-service/entity"
"time"
)
type DeleteResponse struct {
Deleted int
}
type ModuleInfo struct {
Id string
Name string
Active bool
CreatedAt time.Time
LastConnectedAt time.Time
LastDisconnectedAt time.Time
Configs []ConfigModuleInfo `json:",omitempty"`
ConfigSchema *schema.Schema `json:",omitempty"`
Status []Connection `json:",omitempty"`
}
type Connection struct {
LibVersion string
Version string
@@ -31,21 +21,14 @@ type Connection struct {
EstablishedAt time.Time
}
type CommonConfigLinks map[string][]string
type CompiledConfigResponse map[string]interface{}
type DeleteCommonConfigResponse struct {
Deleted bool
Links CommonConfigLinks
}
type CreateUpdateConfigResponse struct {
ErrorDetails map[string]string
Config *ConfigModuleInfo
}
type ConfigModuleInfo struct {
entity.Config
Valid bool
type ModuleInfo struct {
Id int32
Name string
Active bool
CreatedAt time.Time
LastConnectedAt time.Time
LastDisconnectedAt time.Time
Configs []entity.Config `json:",omitempty"`
ConfigSchema *schema.Schema `json:",omitempty"`
Status []Connection `json:",omitempty"`
}
+17 -19
View File
@@ -1,41 +1,39 @@
package entity
import (
"encoding/json"
"github.com/integration-system/isp-lib/config/schema"
"github.com/integration-system/isp-lib/logger"
"time"
)
type ConfigData map[string]interface{}
type Config struct {
tableName string `sql:"?db_schema.configs" json:"-"`
Id string `json:"id"`
Name string `json:"name" valid:"required~Required"`
CommonConfigs []string `json:"commonConfigs" pg:",array"`
Description string `json:"description"`
ModuleId string `json:"moduleId" valid:"required~Required"`
Version int32 `json:"version" sql:",null"`
Active bool `json:"active" sql:",null"`
CreatedAt time.Time `json:"createdAt" sql:",null"`
UpdatedAt time.Time `json:"updatedAt" sql:",null"`
Data ConfigData `json:"data" sql:",notnull"`
func (cd ConfigData) ToJSON() string {
if bytes, err := json.Marshal(cd); err == nil {
return string(bytes)
} else {
logger.Warn("Could not serialize config data to JSON", err)
return "{}"
}
}
type CommonConfig struct {
tableName string `sql:"?db_schema.common_configs" json:"-"`
Id string `json:"id"`
type Config struct {
Id int64 `json:"id"`
Name string `json:"name" valid:"required~Required"`
Description string `json:"description"`
ModuleId int32 `json:"moduleId" valid:"required~Required"`
Version int32 `json:"version" sql:",null"`
Active bool `json:"active" sql:",null"`
CreatedAt time.Time `json:"createdAt" sql:",null"`
UpdatedAt time.Time `json:"updatedAt" sql:",null"`
Data ConfigData `json:"data" sql:",notnull"`
Data ConfigData `json:"data" sql:",notnull"` // Объект конфигурации
}
type ConfigSchema struct {
tableName string `sql:"?db_schema.config_schemas" json:"-"`
Id string `json:"id"`
Id int32
Version string
ModuleId string
ModuleId int32
Schema schema.Schema
CreatedAt time.Time
UpdatedAt time.Time
+13
View File
@@ -0,0 +1,13 @@
package entity
import (
"time"
)
type Instance struct {
Id int32 `json:"id"`
Uuid string `json:"uuid" valid:"required~Required,uuid~must be a valid uuid"`
Name string `json:"name" valid:"required~Required"`
// CreatedAtJson utils.JSONTime `json:"createdAt" sql:"-"`
CreatedAt time.Time `json:"createdAt" sql:",null"`
}
+11 -3
View File
@@ -1,12 +1,20 @@
package entity
import "time"
import (
"time"
)
type Module struct {
tableName string `sql:"?db_schema.modules" json:"-"`
Id string `json:"id"`
Id int32 `json:"id"`
InstanceId int32 `json:"instanceId" valid:"required~Required"`
Name string `json:"name" valid:"required~Required"`
Active bool `json:"active" sql:",null"`
CreatedAt time.Time `json:"createdAt" sql:",null"`
LastConnectedAt time.Time `json:"lastConnectedAt"`
LastDisconnectedAt time.Time `json:"lastDisconnectedAt"`
}
type ModuleInstanceIdentity struct {
Name string `valid:"required~Required"`
Uuid string `valid:"required~Required,uuid~must be a valid uuid"`
}
+257
View File
@@ -0,0 +1,257 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: proto/backend_service.proto
/*
Package isp is a generated protocol buffer package.
It is generated from these files:
proto/backend_service.proto
It has these top-level messages:
Message
*/
package isp
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import _ "google.golang.org/genproto/googleapis/api/annotations"
import google_protobuf1 "github.com/golang/protobuf/ptypes/struct"
import (
context "golang.org/x/net/context"
grpc "google.golang.org/grpc"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
type Message struct {
// Types that are valid to be assigned to Body:
// *Message_StructBody
// *Message_ListBody
Body isMessage_Body `protobuf_oneof:"body"`
}
func (m *Message) Reset() { *m = Message{} }
func (m *Message) String() string { return proto.CompactTextString(m) }
func (*Message) ProtoMessage() {}
func (*Message) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
type isMessage_Body interface {
isMessage_Body()
}
type Message_StructBody struct {
StructBody *google_protobuf1.Struct `protobuf:"bytes,1,opt,name=structBody,oneof"`
}
type Message_ListBody struct {
ListBody *google_protobuf1.ListValue `protobuf:"bytes,2,opt,name=listBody,oneof"`
}
func (*Message_StructBody) isMessage_Body() {}
func (*Message_ListBody) isMessage_Body() {}
func (m *Message) GetBody() isMessage_Body {
if m != nil {
return m.Body
}
return nil
}
func (m *Message) GetStructBody() *google_protobuf1.Struct {
if x, ok := m.GetBody().(*Message_StructBody); ok {
return x.StructBody
}
return nil
}
func (m *Message) GetListBody() *google_protobuf1.ListValue {
if x, ok := m.GetBody().(*Message_ListBody); ok {
return x.ListBody
}
return nil
}
// XXX_OneofFuncs is for the internal use of the proto package.
func (*Message) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
return _Message_OneofMarshaler, _Message_OneofUnmarshaler, _Message_OneofSizer, []interface{}{
(*Message_StructBody)(nil),
(*Message_ListBody)(nil),
}
}
func _Message_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
m := msg.(*Message)
// body
switch x := m.Body.(type) {
case *Message_StructBody:
b.EncodeVarint(1<<3 | proto.WireBytes)
if err := b.EncodeMessage(x.StructBody); err != nil {
return err
}
case *Message_ListBody:
b.EncodeVarint(2<<3 | proto.WireBytes)
if err := b.EncodeMessage(x.ListBody); err != nil {
return err
}
case nil:
default:
return fmt.Errorf("Message.Body has unexpected type %T", x)
}
return nil
}
func _Message_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
m := msg.(*Message)
switch tag {
case 1: // body.structBody
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
msg := new(google_protobuf1.Struct)
err := b.DecodeMessage(msg)
m.Body = &Message_StructBody{msg}
return true, err
case 2: // body.listBody
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
msg := new(google_protobuf1.ListValue)
err := b.DecodeMessage(msg)
m.Body = &Message_ListBody{msg}
return true, err
default:
return false, nil
}
}
func _Message_OneofSizer(msg proto.Message) (n int) {
m := msg.(*Message)
// body
switch x := m.Body.(type) {
case *Message_StructBody:
s := proto.Size(x.StructBody)
n += proto.SizeVarint(1<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(s))
n += s
case *Message_ListBody:
s := proto.Size(x.ListBody)
n += proto.SizeVarint(2<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(s))
n += s
case nil:
default:
panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
}
return n
}
func init() {
proto.RegisterType((*Message)(nil), "isp.Message")
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion4
// Client API for BackendService service
type BackendServiceClient interface {
// ===== SYSTEM =====
Request(ctx context.Context, in *Message, opts ...grpc.CallOption) (*Message, error)
}
type backendServiceClient struct {
cc *grpc.ClientConn
}
func NewBackendServiceClient(cc *grpc.ClientConn) BackendServiceClient {
return &backendServiceClient{cc}
}
func (c *backendServiceClient) Request(ctx context.Context, in *Message, opts ...grpc.CallOption) (*Message, error) {
out := new(Message)
err := grpc.Invoke(ctx, "/isp.BackendService/Request", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// Server API for BackendService service
type BackendServiceServer interface {
// ===== SYSTEM =====
Request(context.Context, *Message) (*Message, error)
}
func RegisterBackendServiceServer(s *grpc.Server, srv BackendServiceServer) {
s.RegisterService(&_BackendService_serviceDesc, srv)
}
func _BackendService_Request_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(Message)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(BackendServiceServer).Request(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/isp.BackendService/Request",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(BackendServiceServer).Request(ctx, req.(*Message))
}
return interceptor(ctx, in, info, handler)
}
var _BackendService_serviceDesc = grpc.ServiceDesc{
ServiceName: "isp.BackendService",
HandlerType: (*BackendServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Request",
Handler: _BackendService_Request_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "proto/backend_service.proto",
}
func init() { proto.RegisterFile("proto/backend_service.proto", fileDescriptor0) }
var fileDescriptor0 = []byte{
// 264 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x2e, 0x28, 0xca, 0x2f,
0xc9, 0xd7, 0x4f, 0x4a, 0x4c, 0xce, 0x4e, 0xcd, 0x4b, 0x89, 0x2f, 0x4e, 0x2d, 0x2a, 0xcb, 0x4c,
0x4e, 0xd5, 0x03, 0x8b, 0x0a, 0x31, 0xe7, 0x16, 0x17, 0x48, 0xc9, 0xa4, 0xe7, 0xe7, 0xa7, 0xe7,
0xa4, 0xea, 0x27, 0x16, 0x64, 0xea, 0x27, 0xe6, 0xe5, 0xe5, 0x97, 0x24, 0x96, 0x64, 0xe6, 0xe7,
0x15, 0x43, 0x94, 0xc0, 0x65, 0xc1, 0xbc, 0xa4, 0xd2, 0x34, 0xfd, 0xe2, 0x92, 0xa2, 0xd2, 0xe4,
0x12, 0x88, 0xac, 0x52, 0x1b, 0x23, 0x17, 0xbb, 0x6f, 0x6a, 0x71, 0x71, 0x62, 0x7a, 0xaa, 0x90,
0x25, 0x17, 0x17, 0x44, 0xce, 0x29, 0x3f, 0xa5, 0x52, 0x82, 0x51, 0x81, 0x51, 0x83, 0xdb, 0x48,
0x5c, 0x0f, 0xa2, 0x5d, 0x0f, 0xa6, 0x5d, 0x2f, 0x18, 0xac, 0xc4, 0x83, 0x21, 0x08, 0x49, 0xb1,
0x90, 0x05, 0x17, 0x47, 0x4e, 0x66, 0x31, 0x44, 0x23, 0x13, 0x58, 0xa3, 0x14, 0x86, 0x46, 0x9f,
0xcc, 0xe2, 0x92, 0xb0, 0xc4, 0x9c, 0xd2, 0x54, 0x0f, 0x86, 0x20, 0xb8, 0x6a, 0x27, 0x36, 0x2e,
0x96, 0xa4, 0xfc, 0x94, 0x4a, 0x23, 0x0f, 0x2e, 0x3e, 0x27, 0x88, 0x17, 0x83, 0x21, 0x3e, 0x14,
0x32, 0xe3, 0x62, 0x0f, 0x4a, 0x2d, 0x2c, 0x4d, 0x2d, 0x2e, 0x11, 0xe2, 0xd1, 0xcb, 0x2d, 0x2e,
0xd0, 0x83, 0xba, 0x53, 0x0a, 0x85, 0xa7, 0xc4, 0xdf, 0x74, 0xf9, 0xc9, 0x64, 0x26, 0x4e, 0x25,
0x16, 0x90, 0xff, 0xad, 0x18, 0xb5, 0x9c, 0xf4, 0xb9, 0xc4, 0x32, 0xf3, 0xf5, 0xd2, 0x8b, 0x0a,
0x92, 0xf5, 0x92, 0xf3, 0xf3, 0xca, 0x52, 0x8b, 0x4a, 0xa0, 0x26, 0x3a, 0x09, 0x3b, 0xa3, 0xf0,
0x03, 0x40, 0x2e, 0x0b, 0x60, 0x4c, 0x62, 0x03, 0x3b, 0xd1, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff,
0x64, 0xa9, 0x7f, 0x65, 0x6a, 0x01, 0x00, 0x00,
}
+122
View File
@@ -0,0 +1,122 @@
// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
// source: proto/backend_service.proto
/*
Package isp is a reverse proxy.
It translates gRPC into RESTful JSON APIs.
*/
package isp
import (
"io"
"net/http"
"github.com/golang/protobuf/proto"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/grpc-ecosystem/grpc-gateway/utilities"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/status"
)
var _ codes.Code
var _ io.Reader
var _ status.Status
var _ = runtime.String
var _ = utilities.NewDoubleArray
func request_BackendService_Request_0(ctx context.Context, marshaler runtime.Marshaler, client BackendServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq Message
var metadata runtime.ServerMetadata
if req.ContentLength > 0 {
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
}
msg, err := client.Request(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
// RegisterBackendServiceHandlerFromEndpoint is same as RegisterBackendServiceHandler but
// automatically dials to "endpoint" and closes the connection when "ctx" gets done.
func RegisterBackendServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) {
conn, err := grpc.Dial(endpoint, opts...)
if err != nil {
return err
}
defer func() {
if err != nil {
if cerr := conn.Close(); cerr != nil {
grpclog.Printf("Failed to close conn to %s: %v", endpoint, cerr)
}
return
}
go func() {
<-ctx.Done()
if cerr := conn.Close(); cerr != nil {
grpclog.Printf("Failed to close conn to %s: %v", endpoint, cerr)
}
}()
}()
return RegisterBackendServiceHandler(ctx, mux, conn)
}
// RegisterBackendServiceHandler registers the http handlers for service BackendService to "mux".
// The handlers forward requests to the grpc endpoint over "conn".
func RegisterBackendServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {
return RegisterBackendServiceHandlerClient(ctx, mux, NewBackendServiceClient(conn))
}
// RegisterBackendServiceHandler registers the http handlers for service BackendService to "mux".
// The handlers forward requests to the grpc endpoint over the given implementation of "BackendServiceClient".
// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "BackendServiceClient"
// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in
// "BackendServiceClient" to call the correct interceptors.
func RegisterBackendServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client BackendServiceClient) error {
mux.Handle("POST", pattern_BackendService_Request_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_BackendService_Request_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_BackendService_Request_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
var (
pattern_BackendService_Request_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0}, []string{"api"}, ""))
)
var (
forward_BackendService_Request_0 = runtime.ForwardResponseMessage
)
+36 -28
View File
@@ -2,31 +2,35 @@ package helper
import (
"github.com/integration-system/isp-lib/structure"
"isp-config-service/controller"
"isp-config-service/controllers"
"isp-config-service/domain"
"isp-config-service/entity"
)
type Handlers struct {
// ===== INSTANCE =====
GetInstances func(identities []int32) ([]entity.Instance, error) `method:"get_instances" group:"instance" inner:"true"`
CreateUpdateInstance func(instance entity.Instance) (*entity.Instance, error) `method:"create_update_instance" group:"instance" inner:"true"`
DeleteInstance func(identities []int32) (*domain.DeleteResponse, error) `method:"delete_instance" group:"instance" inner:"true"`
// ===== MODULE =====
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"`
GetModules func(identities []int32) ([]entity.Module, error) `method:"get_modules" group:"module" inner:"true"`
GetActiveModules func() ([]entity.Module, error) `method:"get_active_modules" group:"module" inner:"true"`
GetConnectedModules func() (map[string]interface{}, error) `method:"get_connected_modules" group:"module" inner:"true"`
CreateUpdateModule func(module entity.Module) (*entity.Module, error) `method:"create_update_module" group:"module" inner:"true"`
DeleteModule func(identities []int32) (*domain.DeleteResponse, error) `method:"delete_module" group:"module" inner:"true"`
GetModulesInfo func(i structure.Isolation) ([]*domain.ModuleInfo, error) `method:"get_modules_info" 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"`
MarkConfigAsActive func(identity domain.ConfigIdRequest) (*entity.Config, error) `method:"mark_config_as_active" group:"config" inner:"true"`
DeleteConfig func(identities []string) (*domain.DeleteResponse, error) `method:"delete_config" group:"config" inner:"true"`
// ===== COMMON CONFIG =====
GetCommonConfigs func(identities []string) []entity.CommonConfig `method:"get_configs" group:"common_config" inner:"true"`
CreateUpdateCommonConfig func(config entity.CommonConfig) (*entity.CommonConfig, error) `method:"create_update_config" group:"common_config" inner:"true"`
DeleteCommonConfig func(req domain.ConfigIdRequest) (*domain.DeleteCommonConfigResponse, error) `method:"delete_config" group:"common_config" inner:"true"`
CompileConfigs func(req domain.CompileConfigsRequest) domain.CompiledConfigResponse `method:"compile" group:"common_config" inner:"true"`
GetLinks func(req domain.ConfigIdRequest) domain.CommonConfigLinks `method:"get_links" group:"common_config" inner:"true"`
GetConfigs func(identities []int64) ([]entity.Config, error) `method:"get_configs" group:"config" inner:"true"`
GetConfigByInstanceUUIDAndModuleName func(request entity.ModuleInstanceIdentity) (*entity.Config, error) `method:"get_config_by_instance_uuid_and_module_name" group:"config" inner:"true"`
CreateUpdateConfig func(config entity.Config) (*entity.Config, error) `method:"create_update_config" group:"config" inner:"true"`
UpdateActiveConfigByInstanceUUIDAndModuleName func(config domain.ConfigInstanceModuleName) (*entity.Config, error) `method:"update_active_config_by_instance_uuid_and_module_name" group:"config" inner:"true"`
MarkConfigAsActive func(identity domain.LongIdentitiesRequest) (*entity.Config, error) `method:"mark_config_as_active" group:"config" inner:"true"`
DeleteConfig func(identities []int64) (*domain.DeleteResponse, error) `method:"delete_config" group:"config" inner:"true"`
// ===== ROUTING =====
GetRoutes func() ([]structure.BackendDeclaration, error) `method:"get_routes" group:"routing" inner:"true"`
GetRoutes func() (map[string]interface{}, error) `method:"get_routes" group:"routing" inner:"true"`
// ===== SCHEMA =====
GetSchemaByModuleId func(domain.GetByModuleIdRequest) (*entity.ConfigSchema, error) `method:"get_by_module_id" group:"schema" inner:"true"`
@@ -34,22 +38,26 @@ type Handlers struct {
func GetHandlers() *Handlers {
return &Handlers{
DeleteModules: controller.Module.DeleteModules,
GetModulesInfo: controller.Module.GetModulesAggregatedInfo,
GetInstances: controllers.GetInstances,
CreateUpdateInstance: controllers.CreateUpdateInstance,
DeleteInstance: controllers.DeleteInstance,
GetActiveConfigByModuleName: controller.Config.GetActiveConfigByModuleName,
CreateUpdateConfig: controller.Config.CreateUpdateConfig,
MarkConfigAsActive: controller.Config.MarkConfigAsActive,
DeleteConfig: controller.Config.DeleteConfigs,
GetModules: controllers.GetModules,
GetActiveModules: controllers.GetActiveModules,
GetConnectedModules: controllers.GetConnectedModules,
CreateUpdateModule: controllers.CreateUpdateModule,
DeleteModule: controllers.DeleteModule,
GetModulesInfo: controllers.GetModulesAggregatedInfo,
GetCommonConfigs: controller.CommonConfig.GetConfigs,
CreateUpdateCommonConfig: controller.CommonConfig.CreateUpdateConfig,
DeleteCommonConfig: controller.CommonConfig.DeleteConfigs,
CompileConfigs: controller.CommonConfig.CompileConfigs,
GetLinks: controller.CommonConfig.GetLinks,
GetConfigs: controllers.GetConfigs,
GetConfigByInstanceUUIDAndModuleName: controllers.GetConfigByInstanceUUIDAndModuleName,
CreateUpdateConfig: controllers.CreateUpdateConfig,
UpdateActiveConfigByInstanceUUIDAndModuleName: controllers.UpdateActiveConfigByInstanceUUIDAndModuleName,
MarkConfigAsActive: controllers.MarkConfigAsActive,
DeleteConfig: controllers.DeleteConfig,
GetRoutes: controller.Routes.GetRoutes,
GetRoutes: controllers.GetRoutes,
GetSchemaByModuleId: controller.Schema.GetByModuleId,
GetSchemaByModuleId: controllers.Schema.GetByModuleId,
}
}
-13
View File
@@ -1,13 +0,0 @@
package holder
import (
etp "github.com/integration-system/isp-etp-go"
"isp-config-service/cluster"
"net/http"
)
var (
ClusterClient *cluster.Client
EtpServer etp.Server
HttpServer *http.Server
)
+195 -174
View File
@@ -1,56 +1,58 @@
package main
import (
"context"
"fmt"
"github.com/integration-system/isp-etp-go"
"github.com/integration-system/isp-lib/backend"
"flag"
"github.com/integration-system/isp-lib/bootstrap"
"github.com/integration-system/isp-lib/config"
"github.com/integration-system/isp-lib/structure"
"github.com/integration-system/isp-lib/utils"
log "github.com/integration-system/isp-log"
"github.com/thecodeteam/goodbye"
"isp-config-service/cluster"
"isp-config-service/codes"
"isp-config-service/conf"
"isp-config-service/controller"
"isp-config-service/helper"
"isp-config-service/holder"
"isp-config-service/model"
"isp-config-service/mux"
"isp-config-service/raft"
"isp-config-service/service"
"isp-config-service/store"
"isp-config-service/store/state"
"isp-config-service/subs"
"net"
"github.com/valyala/fasthttp"
"isp-config-service/domain"
"isp-config-service/module"
"net/http"
"os"
"os/signal"
"time"
"isp-config-service/conf"
"isp-config-service/generated"
"isp-config-service/helper"
"isp-config-service/model"
"isp-config-service/socket"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/integration-system/isp-lib/backend"
"github.com/integration-system/isp-lib/config"
"github.com/integration-system/isp-lib/database"
"github.com/integration-system/isp-lib/logger"
"github.com/integration-system/isp-lib/metric"
"github.com/integration-system/isp-lib/structure"
"github.com/integration-system/isp-lib/utils"
"golang.org/x/net/context"
"google.golang.org/grpc"
)
const (
moduleName = "config"
defaultWsConnectionReadLimit int64 = 4 << 20 // 4 MB
routerModule = "router"
converterModule = "converter"
)
var (
version = "0.1.0"
date = "undefined"
shutdownChan = make(chan struct{})
muxer mux.Mux
configData *conf.Configuration
echoEndpoint *string
version = "0.1.0"
date = "undefined"
)
func init() {
config.InitConfig(&conf.Configuration{})
if utils.LOG_LEVEL != "" {
_ = log.SetLevel(utils.LOG_LEVEL)
}
configData = config.InitConfig(&conf.Configuration{}).(*conf.Configuration)
database.InitDbWithSchema(configData.Database, configData.Database.Schema)
db := database.GetDBManager()
model.InitDbManager(db.Db)
model.SetSchema(configData.Database.Schema)
echoEndpoint = flag.String("echo_endpoint", configData.WS.Grpc.GetAddress(), "endpoint of YourService")
module.Version = version
}
// @title ISP configuration service
// @version 2.0.0
// @version 1.2.0
// @description Сервис управления конфигурацией модулей ISP кластера
// @license.name GNU GPL v3.0
@@ -58,164 +60,183 @@ 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)
address := cfg.GrpcOuterAddress
if address.IP == "" {
ip, err := getOutboundIp()
if err != nil {
panic(err)
}
address.IP = ip
metric.InitCollectors(configData.Metrics, structure.MetricConfiguration{})
metric.InitStatusChecker("routers", checkRouters)
metric.InitStatusChecker("converters", checkConverters)
metric.InitHttpServer(configData.Metrics)
metric.GerHttpRouter().GET("/modules", handleModulesRequest)
createGrpcServer()
createRestServer(runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{OrigName: true, EmitDefaults: true}))
}
func checkRouters() interface{} {
result := make([]string, 0)
instances, err := model.InstanceRep.GetInstances(nil)
if err != nil {
logger.Warn(err)
}
declaration := structure.BackendDeclaration{
ModuleName: cfg.ModuleName,
for _, v := range instances {
list := socket.GetModuleAddressList(v.Uuid, routerModule)
for _, v := range list {
result = append(result, v.GetAddress())
}
}
return result
}
func checkConverters() interface{} {
result := make([]string, 0)
instances, err := model.InstanceRep.GetInstances(nil)
if err != nil {
logger.Warn(err)
}
for _, v := range instances {
list := socket.GetModuleAddressList(v.Uuid, converterModule)
for _, v := range list {
result = append(result, v.GetAddress())
}
}
return result
}
// newGateway returns a new gateway server which translates HTTP into gRPC.
func newGateway(ctx context.Context, opts ...runtime.ServeMuxOption) (http.Handler, error) {
mux := runtime.NewServeMux(opts...)
dialOpts := []grpc.DialOption{grpc.WithInsecure()}
err := isp.RegisterBackendServiceHandlerFromEndpoint(ctx, mux, *echoEndpoint, dialOpts)
if err != nil {
logger.Fatalf("failed to serve rest proxy: %v", err)
}
return mux, nil
}
// Start a GRPC server.
func createGrpcServer() {
// Run our server in a goroutine so that it doesn't block.
handlers := helper.GetHandlers()
addr := structure.AddressConfiguration{IP: configData.WS.Grpc.IP, Port: configData.WS.Grpc.Port}
addrOuter := structure.AddressConfiguration{IP: configData.GrpcOuterAddress.IP, Port: configData.GrpcOuterAddress.Port}
backend.StartBackendGrpcServer(addr, backend.GetDefaultService(configData.ModuleName, handlers))
enndpoints := backend.GetEndpoints(configData.ModuleName, handlers)
socket.SetBackendMethods(&structure.BackendDeclaration{
ModuleName: configData.ModuleName,
Version: version,
LibVersion: bootstrap.LibraryVersion,
Endpoints: endpoints,
Address: address,
}
model.DbClient.ReceiveConfiguration(cfg.Database)
httpListener, raftListener, err := initMultiplexer(cfg.WS.Rest)
if err != nil {
log.Fatalf(codes.InitMuxError, "init mux: %v", err)
}
_, raftStore := initRaft(raftListener, cfg.Cluster, declaration)
initWebsocket(ctx, cfg.WS.WsConnectionReadLimitKB, httpListener, raftStore)
initGrpc(cfg.WS.Grpc, raftStore)
defer goodbye.Exit(ctx, -1)
goodbye.Notify(ctx)
goodbye.Register(onShutdown)
<-shutdownChan
Endpoints: enndpoints,
Address: addrOuter,
})
logger.Infof("EXPORTED MODULE METHODS: %v, module_name: %s, version: %s",
enndpoints, configData.ModuleName, version)
}
func initMultiplexer(addressConfiguration structure.AddressConfiguration) (net.Listener, net.Listener, error) {
outerAddr, err := net.ResolveTCPAddr("tcp4", addressConfiguration.GetAddress())
if err != nil {
return nil, nil, fmt.Errorf("resolve outer address: %v", err)
}
tcpListener, err := net.ListenTCP("tcp4", outerAddr)
if err != nil {
return nil, nil, fmt.Errorf("create tcp transport: %v", err)
}
muxer = mux.New(tcpListener)
httpListener := muxer.Match(mux.HTTP1())
raftListener := muxer.Match(mux.Any())
go func() {
if err := muxer.Serve(); err != nil {
log.Fatalf(codes.InitMuxError, "serve mux: %v", err)
}
}()
return httpListener, raftListener, nil
}
func initWebsocket(ctx context.Context, wsConnectionReadLimitKB int64, listener net.Listener, raftStore *store.Store) {
connectionReadLimit := defaultWsConnectionReadLimit
if wsConnectionReadLimitKB > 0 {
connectionReadLimit = wsConnectionReadLimitKB << 10
}
etpConfig := etp.ServerConfig{
InsecureSkipVerify: true,
ConnectionReadLimit: connectionReadLimit,
}
etpServer := etp.NewServer(ctx, etpConfig)
subs.NewSocketEventHandler(etpServer, raftStore).SubscribeAll()
// Start a HTTP server.
func createRestServer(opts ...runtime.ServeMuxOption) {
mux := http.NewServeMux()
mux.HandleFunc("/isp-etp/", etpServer.ServeHttp)
httpServer := &http.Server{Handler: mux}
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// === Socket.IO ===
mux.Handle("/socket.io/", socket.Get())
// === REST ===
/*mux.Handle("/swagger/", controller.StaticHandler(
http.StripPrefix(
"/swagger/", http.FileServer(
http.Dir(path.Join(executableFileDir, "static", "swagger-ui"))))))*/
gw, err := newGateway(ctx, opts...)
if err != nil {
logger.Fatalf("failed to serve: %v", err)
}
mux.Handle("/", gw)
/*r.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
})*/
var wait time.Duration
flag.DurationVar(&wait, "graceful-timeout", time.Second*15,
"the duration for which the server gracefully wait for existing connections to finish - e.g. 15s or 1m")
flag.Parse()
restAddress := configData.WS.Rest.GetAddress()
logger.Infof("Serving at %s ...", restAddress)
srv := &http.Server{
Addr: restAddress,
// Good practice to set timeouts to avoid Slowloris attacks.
WriteTimeout: time.Second * 15,
ReadTimeout: time.Second * 15,
IdleTimeout: time.Second * 60,
Handler: mux, // Pass our instance of gorilla/mux in.
}
go func() {
if err := httpServer.Serve(listener); err != nil && err != http.ErrServerClosed {
log.Fatalf(codes.StartHttpServerError, "http server closed: %v", err)
if err := srv.ListenAndServe(); err != nil {
logger.Fatal(err)
}
}()
holder.EtpServer = etpServer
holder.HttpServer = httpServer
c := make(chan os.Signal, 1)
// We'll accept graceful shutdowns when quit via SIGINT (Ctrl+C)
// SIGKILL, SIGQUIT or SIGTERM (Ctrl+/) will not be caught.
signal.Notify(c, os.Interrupt)
// Block until we receive our signal.
<-c
// Create a deadline to wait for.
ctx, cancel = context.WithTimeout(context.Background(), wait)
defer cancel()
// Doesn't block if no connections, but will otherwise wait
// until the timeout deadline.
_ = srv.Shutdown(ctx)
// Optionally, you could run srv.Shutdown in a goroutine and block on
// <-ctx.Done() if your application should wait for other services
// to finalize based on context cancellation.
logger.Info("shutting down")
os.Exit(0)
}
func initRaft(listener net.Listener, clusterCfg conf.ClusterConfiguration, declaration structure.BackendDeclaration) (*cluster.Client, *store.Store) {
raftState, err := store.NewStateFromRepository()
func handleModulesRequest(ctx *fasthttp.RequestCtx) {
instances, err := model.InstanceRep.GetInstances(nil)
if err != nil {
log.Fatal(codes.RestoreFromRepositoryError, err)
return nil, nil
logger.Warn(err)
ctx.Error("internal server error", http.StatusInternalServerError)
return
}
raftStore := store.NewStateStore(raftState)
r, err := raft.NewRaft(listener, clusterCfg, raftStore)
if err != nil {
log.Fatalf(codes.InitRaftError, "unable to create raft server. %v", err)
return nil, nil
}
clusterClient := cluster.NewRaftClusterClient(r, declaration, func(address string) {
raftStore.VisitState(func(s state.WritableState) {
cfg := config.Get().(*conf.Configuration)
addr, err := net.ResolveTCPAddr("tcp", address)
if err != nil {
panic(err) // must never occured
}
port := cfg.GrpcOuterAddress.Port
addressConfiguration := structure.AddressConfiguration{Port: port, IP: addr.IP.String()}
back := structure.BackendDeclaration{ModuleName: cfg.ModuleName, Address: addressConfiguration}
log.WithMetadata(map[string]interface{}{"declaration": back}).
Debugf(0, "delete disconnected leader's declaration")
service.ClusterMeshService.HandleDeleteBackendDeclarationCommand(back, s)
})
})
holder.ClusterClient = clusterClient
if clusterCfg.BootstrapCluster {
err = r.BootstrapCluster() // err can be ignored
result := make(map[string][]*domain.ModuleInfo, len(instances))
for _, i := range instances {
info, err := module.GetAggregatedModuleInfo(i.Uuid)
if err != nil {
log.Errorf(codes.BootstrapClusterError, "bootstrap cluster. %v", err)
logger.Warn(err)
continue
}
for _, inf := range info {
inf.ConfigSchema = nil
inf.Configs = nil
for i := range inf.Status {
s := &inf.Status[i]
s.Endpoints = nil
}
}
result[i.Uuid] = info
}
return clusterClient, raftStore
}
func initGrpc(bindAddress structure.AddressConfiguration, raftStore *store.Store) {
controller.Routes = controller.NewRoutes(raftStore)
controller.Schema = controller.NewSchema(raftStore)
controller.Module = controller.NewModule(raftStore)
controller.Config = controller.NewConfig(raftStore)
controller.CommonConfig = controller.NewCommonConfig(raftStore)
defaultService := backend.GetDefaultService(moduleName, helper.GetHandlers())
backend.StartBackendGrpcServer(bindAddress, defaultService)
}
func onShutdown(ctx context.Context, _ os.Signal) {
defer close(shutdownChan)
backend.StopGrpcServer()
holder.EtpServer.Close()
if err := holder.HttpServer.Shutdown(ctx); err != nil {
log.Warnf(codes.ShutdownHttpServerError, "http server shutdown err: %v", err)
if bytes, err := utils.ConvertGoToBytes(result); err != nil {
logger.Warn(err)
ctx.Error("internal server error", http.StatusInternalServerError)
} else {
log.Info(codes.ShutdownHttpServerInfo, "http server shutdown success")
ctx.SetStatusCode(http.StatusOK)
ctx.SetContentType("application/json; charset=utf-8")
ctx.SetBody(bytes)
}
if err := holder.ClusterClient.Shutdown(); err != nil {
log.Warnf(codes.RaftShutdownError, "raft shutdown err: %v", err)
} else {
log.Info(codes.RaftShutdownInfo, "raft shutdown success")
}
_ = muxer.Close()
}
func getOutboundIp() (string, error) {
conn, err := net.Dial("udp", "9.9.9.9:80")
if err != nil {
return "", err
}
defer conn.Close()
return conn.LocalAddr().(*net.UDPAddr).IP.To4().String(), nil
}
-46
View File
@@ -1,46 +0,0 @@
-- +goose Up
DROP TABLE instances CASCADE;
DROP TRIGGER update_config_create_time ON configs;
DROP TRIGGER deactivate_config on configs;
DROP TRIGGER update_schema_create_time ON config_schemas;
DROP TRIGGER update_customer_modtime ON modules;
ALTER TABLE configs
DROP CONSTRAINT "FK_configs_moduleId_modules_id";
ALTER TABLE config_schemas
DROP CONSTRAINT "fk_module_id__module_id";
ALTER TABLE configs
ALTER COLUMN id TYPE varchar(255),
ALTER COLUMN module_id TYPE varchar(255),
ADD COLUMN common_configs varchar(255)[] NOT NULL DEFAULT '{}';
ALTER TABLE config_schemas
ALTER COLUMN module_id TYPE varchar(255),
ALTER COLUMN id TYPE varchar(255);
ALTER TABLE modules
ALTER COLUMN id TYPE varchar(255),
DROP COLUMN active,
DROP COLUMN instance_id;
CREATE TABLE common_configs
(
id VARCHAR(255) NOT NULL PRIMARY KEY,
name VARCHAR(255) NOT NULL DEFAULT 'unnamed',
description TEXT,
created_at timestamp NOT NULL DEFAULT (now() at time zone 'utc'),
updated_at timestamp NOT NULL DEFAULT (now() at time zone 'utc'),
data jsonb NOT NULL DEFAULT '{}'
);
-- +goose Down
DROP TABLE common_configs;
@@ -0,0 +1,5 @@
-- +goose Up
CREATE schema if NOT EXISTS "config_service";
-- +goose Down
DROP schema if EXISTS config_service CASCADE;
@@ -0,0 +1,47 @@
-- +goose Up
CREATE TABLE instances (
id serial4 NOT NULL PRIMARY KEY,
uuid UUID NOT NULL,
"name" varchar(255) NOT NULL,
created_at timestamp DEFAULT (now() at time zone 'utc') NOT NULL
);
-- +goose StatementBegin
CREATE OR REPLACE FUNCTION update_created_modified_column_date()
RETURNS TRIGGER AS
$body$
BEGIN
IF TG_OP = 'UPDATE' THEN
NEW.created_at = OLD.created_at;
NEW.updated_at = (now() at time zone 'utc');
ELSIF TG_OP = 'INSERT' THEN
NEW.updated_at = (now() at time zone 'utc');
END IF;
RETURN NEW;
END;
$body$ LANGUAGE plpgsql;
-- +goose StatementEnd
-- +goose StatementBegin
CREATE OR REPLACE FUNCTION update_created_column_date()
RETURNS TRIGGER AS
$body$
BEGIN
IF TG_OP = 'UPDATE' THEN
NEW.created_at = OLD.created_at;
ELSIF TG_OP = 'INSERT' THEN
NEW.created_at = (now() at time zone 'utc');
END IF;
RETURN NEW;
END;
$body$ LANGUAGE plpgsql;
-- +goose StatementEnd
CREATE TRIGGER update_customer_modtime BEFORE INSERT OR UPDATE ON instances
FOR EACH ROW EXECUTE PROCEDURE update_created_column_date();
ALTER TABLE instances ADD CONSTRAINT "UQ_instances_uuid" UNIQUE ("uuid");
-- +goose Down
DROP TABLE instances;
@@ -0,0 +1,24 @@
-- +goose Up
CREATE TABLE modules (
id serial4 NOT NULL PRIMARY KEY,
instance_id int4 NOT NULL,
"name" varchar(255) NOT NULL,
"active" bool DEFAULT true,
created_at timestamp DEFAULT (now() at time zone 'utc') NOT NULL,
last_connected_at timestamp,
last_disconnected_at timestamp
);
ALTER TABLE modules
ADD CONSTRAINT "FK_modules_instanceId_instances_id"
FOREIGN KEY ("instance_id") REFERENCES instances ("id")
ON DELETE CASCADE ON UPDATE CASCADE;
CREATE INDEX IX_modules_instanceId ON modules USING hash (instance_id);
CREATE TRIGGER update_customer_modtime BEFORE INSERT OR UPDATE ON modules
FOR EACH ROW EXECUTE PROCEDURE update_created_column_date();
ALTER TABLE modules ADD CONSTRAINT "UQ_modules_instanceId_name" UNIQUE ("instance_id", "name");
-- +goose Down
DROP TABLE modules;
@@ -0,0 +1,70 @@
-- +goose Up
CREATE TABLE configs (
id serial8 NOT NULL PRIMARY KEY,
module_id int4 NOT NULL,
"version" int4 NOT NULL,
"active" bool DEFAULT false,
created_at timestamp DEFAULT (now() at time zone 'utc') NOT NULL,
updated_at timestamp DEFAULT (now() at time zone 'utc') NOT NULL,
"data" jsonb NOT NULL DEFAULT '{}'
);
ALTER TABLE configs
ADD CONSTRAINT "FK_configs_moduleId_modules_id"
FOREIGN KEY ("module_id") REFERENCES modules ("id")
ON DELETE CASCADE ON UPDATE CASCADE;
CREATE INDEX IX_configs_moduleId ON configs USING hash (module_id);
-- +goose StatementBegin
CREATE OR REPLACE FUNCTION deactivate_config()
RETURNS TRIGGER AS
$body$
DECLARE
last_version integer;
BEGIN
NEW.updated_at = (now() at time zone 'utc');
IF TG_OP = 'INSERT'
THEN
EXECUTE format('
SELECT version
FROM %I.configs
WHERE module_id = ' || NEW.module_id || '
ORDER BY created_at DESC
LIMIT 1;
', TG_TABLE_SCHEMA) INTO last_version;
IF last_version IS NOT NULL
THEN
NEW.version = last_version + 1;
ELSE
NEW.version = 1;
END IF;
ELSE
NEW.version = OLD.version;
NEW.created_at = OLD.created_at;
END IF;
IF NEW.active = TRUE
THEN
EXECUTE format('
UPDATE %I.configs
SET active = FALSE,
updated_at = (now() at time zone ''utc'')
WHERE active = TRUE AND ' || NEW.id || ' != id AND module_id = ' || NEW.module_id || ';
', TG_TABLE_SCHEMA);
END IF;
RETURN NEW;
END;
$body$ LANGUAGE plpgsql;
-- +goose StatementEnd
CREATE TRIGGER "deactivate_config"
BEFORE INSERT OR UPDATE ON configs
FOR EACH ROW EXECUTE PROCEDURE deactivate_config();
CREATE TRIGGER update_config_create_time BEFORE INSERT OR UPDATE ON configs
FOR EACH ROW EXECUTE PROCEDURE update_created_column_date();
-- +goose Down
DROP TABLE configs;
DROP FUNCTION deactivate_config;
@@ -0,0 +1,6 @@
-- +goose Up
INSERT INTO instances VALUES (1, 'bf482806-0c3d-4e0d-b9d4-12c037b12d70', 'main', NULL);
SELECT setval(pg_get_serial_sequence('instances', 'id'), 2, FALSE);
-- +goose Down
DELETE FROM instances WHERE id=1
@@ -0,0 +1,10 @@
-- +goose Up
INSERT INTO modules VALUES (1, 1, 'auth', 't', NULL, NULL, NULL);
INSERT INTO modules VALUES (2, 1, 'converter', 't', NULL, NULL, NULL);
INSERT INTO modules VALUES (3, 1, 'router', 't', NULL, NULL, NULL);
INSERT INTO modules VALUES (4, 1, 'system', 't', NULL, NULL, NULL);
INSERT INTO modules VALUES (5, 1, 'admin', 't', NULL, NULL, NULL);
SELECT setval(pg_get_serial_sequence('modules', 'id'), 6, FALSE);
-- +goose Down
DELETE FROM modules WHERE id IN (1,2,3,4,5);
@@ -0,0 +1,11 @@
-- +goose Up
INSERT INTO modules VALUES (6, 1, 'user', 't', NULL, NULL, NULL);
INSERT INTO modules VALUES (7, 1, 'mobile', 't', NULL, NULL, NULL);
INSERT INTO modules VALUES (8, 1, 'awip', 't', NULL, NULL, NULL);
INSERT INTO modules VALUES (9, 1, 'mongo-backend', 't', NULL, NULL, NULL);
INSERT INTO modules VALUES (10, 1, 'sql-backend', 't', NULL, NULL, NULL);
INSERT INTO modules VALUES (11, 1, 'events', 't', NULL, NULL, NULL);
SELECT setval(pg_get_serial_sequence('modules', 'id'), 12, FALSE);
-- +goose Down
DELETE FROM modules WHERE id IN (6,7,8,9,10,11);
@@ -0,0 +1,124 @@
-- +goose Up
set migration.db_host = 'isp-pgsql';
set migration.db_port = '5432';
set migration.db_dbname = 'isp-test';
set migration.db_user = 'isp-test';
set migration.db_pass = '123321';
set migration.redis_host = 'isp-redis';
set migration.redis_port = '5672';
set migration.admin_token_secret = 'secret';
-- auth
INSERT INTO configs VALUES (1, 1, NULL, 't', NULL, NULL, (format('{
"jwt": {
"secret": "%s"
},
"redis": {
"ip": "%s",
"port": %s
},
"header": {
"token": {
"user": "X-USER-TOKEN",
"admin": "X-AUTH-ADMIN",
"device": "X-DEVICE-TOKEN",
"application": "X-APPLICATION-TOKEN"
},
"identity": {
"device": "X-DEVICE-IDENTITY",
"domain": "X-DOMAIN-IDENTITY",
"system": "X-SYSTEM-IDENTITY",
"service": "X-SERVICE-IDENTITY",
"application": "X-APPLICATION-IDENTITY",
"user": "X-USER-IDENTITY"
}
},
"unauthorized.html": "<HTML><BODY><H1>401 Unauthorized BAD CREDENTIALS</H1></BODY></HTML>"
}',
current_setting('migration.admin_token_secret'),
current_setting('migration.redis_host'),
current_setting('migration.redis_port')
))::jsonb);
-- converter
INSERT INTO configs VALUES (2, 2, NULL, 't', NULL, NULL, ('{"metrics": {"gc": true, "memory": true, "address": {"ip": "0.0.0.0", "path": "/metrics", "port": "9553"}}}')::jsonb);
-- router
INSERT INTO configs VALUES (3, 3, NULL, 't', NULL, NULL, ('{
"metrics": {
"gc": true,
"memory": true,
"address": {
"port": "9554",
"ip": "0.0.0.0",
"path": "/metrics"
}
}
}')::jsonb);
-- system
INSERT INTO configs VALUES (4, 4, NULL, 't', NULL, NULL, (format('{
"dB": {
"password": "%s",
"username": "%s",
"createSchema": true,
"port": "%s",
"schema": "system_service",
"address": "%s",
"database": "%s"
},
"metrics": {
"address": {
"ip": "0.0.0.0",
"path": "/metrics",
"port": "9555"
},
"gc": true,
"memory": true
},
"redisAddress": {
"ip": "%s",
"port": "%s"
}
}', current_setting('migration.db_pass'),
current_setting('migration.db_user'),
current_setting('migration.db_port'),
current_setting('migration.db_host'),
current_setting('migration.db_dbname'),
current_setting('migration.redis_host'),
current_setting('migration.redis_port')
))::jsonb);
-- admin
INSERT INTO configs VALUES (5, 5, NULL, 't', NULL, NULL, (format('{
"metrics": {
"gc": true,
"memory": true,
"address": {
"path": "/metrics",
"port": "9557",
"ip": "0.0.0.0"
}
},
"database": {
"password": "%s",
"username": "%s",
"createSchema": true,
"port": "%s",
"schema": "admin_service",
"address": "%s",
"database": "%s"
},
"secretKey": "%s"
}',
current_setting('migration.db_pass'),
current_setting('migration.db_user'),
current_setting('migration.db_port'),
current_setting('migration.db_host'),
current_setting('migration.db_dbname'),
current_setting('migration.admin_token_secret')
))::jsonb);
SELECT setval(pg_get_serial_sequence('configs', 'id'), 6, FALSE);
-- +goose Down
DELETE FROM configs WHERE id IN (1,2,3,4,5)
@@ -0,0 +1,127 @@
-- +goose Up
set migration.db_host = 'isp-pgsql';
set migration.db_port = '5432';
set migration.db_dbname = 'isp-test';
set migration.db_user = 'isp-test';
set migration.db_pass = '123321';
set migration.redis_host = 'isp-redis';
set migration.redis_port = '6379';
-- user
INSERT INTO configs VALUES (6, 6, NULL, 't', NULL, NULL, (format('{
"metrics": {"gc": true, "memory": true, "address": {"ip": "0.0.0.0", "path": "/metrics", "port": "9556"}},
"database": {
"username": "%s",
"createSchema": true,
"port": "%s",
"schema": "user_service",
"address": "%s",
"database": "%s",
"password": "%s"
},
"redisAddress": {
"ip": "%s",
"port": "%s"
},
"userTokenExpireMs": -1,
"authSmsSystemSender": "",
"authSmsTextTemplate": "Your code {{code}}",
"deviceTokenExpireMs": -1,
"authSmsShortCodeLength": 4,
"authSmsShortCodeExpireMs": 300000
}', current_setting('migration.db_user'),
current_setting('migration.db_port'),
current_setting('migration.db_host'),
current_setting('migration.db_dbname'),
current_setting('migration.db_pass'),
current_setting('migration.redis_host'),
current_setting('migration.redis_port')
)) :: jsonb);
-- mobile
INSERT INTO configs VALUES (7, 7, NULL, 't', NULL, NULL, ('{"database": {' ||
'"port": "' || current_setting('migration.db_port') || '", ' ||
'"schema": "mobile_service", ' ||
'"address": "' || current_setting('migration.db_host') || '", ' ||
'"database": "' || current_setting('migration.db_dbname') || '", ' ||
'"password": "' || current_setting('migration.db_pass') || '", ' ||
'"username": "' || current_setting('migration.db_user') || '", ' ||
'"createSchema": true}, ' ||
'"metrics": {"gc": true, "memory": true, "address": {"ip": "0.0.0.0", "path": "/metrics", "port": "9562"}}' ||
'}')::jsonb);
-- awip
INSERT INTO configs VALUES (8, 8, NULL, 't', NULL, NULL, '{
"backends": [
{
"id": "450e754f-aafb-4a9c-8d87-23c6a2da9833",
"url": "http://{{ cname }}-nginx.{{ main_domain }}:18888/ru.isp.starter.awip.backend.ws/backend?wsdl",
"name": "citymatica_user_new",
"wrapList": true,
"createDate": "2018-09-07T09:41:03.853Z",
"clientPoolSize": 0,
"requestTimeout": 30000,
"systemIdentity": "1"
},
{
"id": "74d76314-b28b-11e8-96f8-529269fb1459",
"url": "http://{{ cname }}-nginx.{{ main_domain }}:18880/ru.mp.storage.backend.ws/backend?wsdl",
"name": "citymatica_user_old",
"wrapList": true,
"createDate": "2018-09-07T09:41:03.853Z",
"clientPoolSize": 0,
"requestTimeout": 30000,
"systemIdentity": "1"
},
{
"id": "74d7659e-b28b-11e8-96f8-529269fb1459",
"url": "http://{{ cname }}-nginx.{{ main_domain }}:18890/ru.isp.starter.awip.backend.ws/backend?wsdl",
"name": "citymatica_user_object_storage",
"wrapList": true,
"createDate": "2018-09-07T09:41:03.853Z",
"clientPoolSize": 0,
"requestTimeout": 30000,
"systemIdentity": "1"
},
{
"id": "74d75cc0-b28b-11e8-96f8-529269fb1459",
"url": "http://{{ cname }}-nginx.{{ main_domain }}:18891/ru.isp.starter.awip.backend.ws/backend?wsdl",
"name": "citymatica_user_events",
"wrapList": true,
"createDate": "2018-09-07T09:41:03.853Z",
"clientPoolSize": 0,
"requestTimeout": 30000,
"systemIdentity": "1"
},
{
"id": "d5575047-6588-46d9-be58-b487d42d217c",
"url": "http://{{ cname }}-nginx.{{ main_domain }}:18889/ru.isp.starter.awip.backend.ws/backend?wsdl",
"name": "citymatica_operator",
"wrapList": true,
"createDate": "2018-09-07T09:41:03.853Z",
"clientPoolSize": 0,
"requestTimeout": 30000,
"systemIdentity": "1"
},
{
"id": "74d76094-b28b-11e8-96f8-529269fb1459",
"url": "http://{{ cname }}-nginx.{{ main_domain }}:18895/ru.isp.starter.awip.backend.ws/backend?wsdl",
"name": "citymatica_operator_metrics",
"wrapList": true,
"createDate": "2018-09-07T09:41:03.853Z",
"clientPoolSize": 0,
"requestTimeout": 30000,
"systemIdentity": "1"
}
]
}');
-- mongo-backend
INSERT INTO configs VALUES (9, 9, NULL, 't', NULL, NULL, '{"connections": [],"metrics": {"gc": true, "memory": true, "address": {"ip": "0.0.0.0", "path": "/metrics", "port": "9563"}}}');
-- sql-backend
INSERT INTO configs VALUES (10, 10, NULL, 't', NULL, NULL, '{"connections": [], "metrics": {"gc": true, "memory": true, "address": {"ip": "0.0.0.0", "path": "/metrics", "port": "9566"}}}');
-- events
INSERT INTO configs VALUES (11, 11, NULL, 't', NULL, NULL, '{"eventRoutes": [{"handlers": {}, "applicationGroupId": 1}, {"handlers": {}, "applicationGroupId": 5}], "queueEndpoints": []}');
SELECT setval(pg_get_serial_sequence('configs', 'id'), 12, FALSE);
-- +goose Down
DELETE FROM configs WHERE id IN (6,7,8,9,10,11)
@@ -0,0 +1,9 @@
-- +goose Up
ALTER TABLE configs
ADD COLUMN name VARCHAR(255) NOT NULL DEFAULT 'unnamed',
ADD COLUMN description TEXT;
-- +goose Down
ALTER TABLE configs
DROP COLUMN name,
DROP COLUMN description;
@@ -0,0 +1,23 @@
-- +goose Up
CREATE TABLE config_schemas (
id SERIAL4 PRIMARY KEY,
module_id INTEGER NOT NULL,
version VARCHAR(255) NOT NULL,
schema JSONB NOT NULL DEFAULT '{}',
created_at TIMESTAMP NOT NULL DEFAULT (now() at time zone 'utc'),
updated_at TIMESTAMP NOT NULL DEFAULT (now() at time zone 'utc'),
CONSTRAINT FK_module_id__module_id FOREIGN KEY (module_id)
REFERENCES modules (id) ON UPDATE CASCADE ON DELETE CASCADE
);
CREATE TRIGGER update_schema_create_time
BEFORE INSERT OR UPDATE
ON config_schemas
FOR EACH ROW EXECUTE PROCEDURE update_created_modified_column_date();
CREATE INDEX IX_schemes_moduleId
ON config_schemas
USING hash (module_id);
-- +goose Down
DROP TABLE config_schemas;
@@ -0,0 +1,42 @@
-- +goose Up
set migration.db_host = 'isp-pgsql';
set migration.db_port = '5432';
set migration.db_dbname = 'isp-test';
set migration.db_user = 'isp-test';
set migration.db_pass = '123321';
WITH moduleVar AS (
INSERT INTO modules (instance_id, name, active) VALUES (1, 'template', 't') RETURNING id
)
INSERT INTO configs (module_id, active, data) VALUES (
(SELECT id FROM moduleVar),
't',
('{"database": {' ||
'"port": "' || current_setting('migration.db_port') || '", ' ||
'"schema": "template_service", ' ||
'"address": "' || current_setting('migration.db_host') || '", ' ||
'"database": "' || current_setting('migration.db_dbname') || '", ' ||
'"password": "' || current_setting('migration.db_pass') || '", ' ||
'"username": "' || current_setting('migration.db_user') || '", ' ||
'"createSchema": true}, "defaultLanguage": "en", ' ||
'"metrics": {"gc": true, "memory": true, "address": {"ip": "0.0.0.0", "path": "/metrics", "port": "9567"}}' ||
'}')::jsonb);
WITH moduleVar AS (
INSERT INTO modules (instance_id, name, active) VALUES (1, 'message-bundle', 't') RETURNING id
)
INSERT INTO configs (module_id, active, data) VALUES (
(SELECT id FROM moduleVar),
't',
('{"database": {' ||
'"port": "' || current_setting('migration.db_port') || '", ' ||
'"schema": "message_bundle_service", ' ||
'"address": "' || current_setting('migration.db_host') || '", ' ||
'"database": "' || current_setting('migration.db_dbname') || '", ' ||
'"password": "' || current_setting('migration.db_pass') || '", ' ||
'"username": "' || current_setting('migration.db_user') || '", ' ||
'"createSchema": true}, "defaultLanguage": "en", ' ||
'"metrics": {"gc": true, "memory": true, "address": {"ip": "0.0.0.0", "path": "/metrics", "port": "9560"}}' ||
'}')::jsonb);
-- +goose Down
@@ -0,0 +1,88 @@
-- +goose Up
set migration.nats_host = 'isp-nats';
set migration.nats_port = '4223';
set migration.nats_cluster_id = 'test-cluster';
WITH moduleVar AS (INSERT INTO modules (instance_id, name, active) VALUES (1, 'mobile-push', 't') RETURNING id)
INSERT INTO configs (module_id, active, data)
VALUES ((SELECT id FROM moduleVar), 't', (
format('{
"metrics": {"gc": true, "memory": true, "address": {"ip": "0.0.0.0", "path": "/metrics", "port": "9561"}},
"firebaseConfig": {
"token_uri": "https://accounts.google.com/o/oauth2/token",
"client_id": "",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"client_email": "firebase-adminsdk-f70qo@test-ccdab.iam.gserviceaccount.com",
"private_key": "",
"private_key_id": "",
"project_id": "test-ccdab",
"type": "service_account",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-f70qo%%40test-ccdab.iam.gserviceaccount.com"
},
"concurrentSendersCount": 6,
"natsConfig": {
"address": {
"port": "%s",
"ip": "%s"
},
"clusterId": "%s"
}
}', current_setting('migration.nats_port'),
current_setting('migration.nats_host'),
current_setting('migration.nats_cluster_id')
)) :: jsonb);
WITH moduleVar AS (INSERT INTO modules (instance_id, name, active) VALUES (1, 'sms', 't') RETURNING id)
INSERT INTO configs (module_id, active, data)
VALUES ((SELECT id FROM moduleVar), 't', (format('{
"natsConfig": {
"clusterId": "%s",
"address": {
"ip": "%s",
"port": "%s"
}
},
"smppClients": [
{
"default": true,
"poolSize": 1,
"connection": {
"password": "",
"user": "isp",
"address": {
"ip": "5.187.0.65",
"port": "9931"
}
},
"ResponseTimeoutMs": 5000,
"concurrentSendersCount": 2,
"name": "smsc"
}
],
"metrics": {"gc": true, "memory": true, "address": {"ip": "0.0.0.0", "path": "/metrics", "port": "9565"}}
}', current_setting('migration.nats_cluster_id'),
current_setting('migration.nats_host'),
current_setting('migration.nats_port')
)) :: jsonb);
WITH moduleVar AS (INSERT INTO modules (instance_id, name, active) VALUES (1, 'email', 't') RETURNING id)
INSERT INTO configs (module_id, active, data)
VALUES ((SELECT id FROM moduleVar), 't', (format('{
"natsConfig": {
"clusterId": "%s",
"address": {
"ip": "%s",
"port": "%s"
}
},
"smtpClients": [
],
"metrics": {"gc": true, "memory": true, "address": {"ip": "0.0.0.0", "path": "/metrics", "port": "9558"}}
}', current_setting('migration.nats_cluster_id'),
current_setting('migration.nats_host'),
current_setting('migration.nats_port')
)) :: jsonb);
-- +goose Down
@@ -0,0 +1,27 @@
-- +goose Up
WITH moduleVar AS (INSERT INTO modules (instance_id, name, active) VALUES (1, 'file-storage', 't')
RETURNING id)
INSERT INTO configs (module_id, active, data)
VALUES ((SELECT id FROM moduleVar), 't', '{
"imageSizeList": [
75,
130,
200,
320,
510,
604,
807
],
"rootDirectory": "./files/",
"maxRequestBodySizeInBytes": 1073741824,
"metrics": {"gc": true, "memory": true, "address": {"ip": "0.0.0.0", "path": "/metrics", "port": "9559"}}
}' :: jsonb);
WITH moduleVar AS (INSERT INTO modules (instance_id, name, active) VALUES (1, 'rest-backend', 't')
RETURNING id)
INSERT INTO configs (module_id, active, data)
VALUES ((SELECT id FROM moduleVar), 't', '{
"backends": [], "metrics": {"gc": true, "memory": true, "address": {"ip": "0.0.0.0", "path": "/metrics", "port": "9564"}}
}' :: jsonb);
-- +goose Down
@@ -0,0 +1,88 @@
-- +goose Up
set migrationWrite.db_host = 'isp-pgsql';
set migrationWrite.db_port = '5432';
set migrationWrite.db_dbname = 'isp-test';
set migrationWrite.db_user = 'isp-test';
set migrationWrite.db_pass = '123321';
set migrationRead.db_host = 'isp-pgsql';
set migrationRead.db_port = '5432';
set migrationRead.db_dbname = 'isp-test';
set migrationRead.db_user = 'isp-test';
set migrationRead.db_pass = '123321';
set "rabbit.host" = 'isp-rabbit';
set "rabbit.port" = '5672';
set "rabbit.user" = 'guest';
set "rabbit.password" = 'guest';
WITH moduleVar AS (
INSERT INTO modules (instance_id, name, active) VALUES (1, 'mdm', 't') RETURNING id
)
INSERT INTO configs (module_id, active, data) VALUES (
(SELECT id FROM moduleVar),
't',
((format('{
"queue": {
"exchange": "notifications",
"notifierQueue": "notifier.queue",
"searcherQueue": "searcher.queue"
},
"rabbit": {
"user": "%s",
"address": {
"ip": "%s",
"port": "%s"
},
"password": "%s"
},
"metrics": {
"gc": true,
"memory": true,
"address": {
"ip": "0.0.0.0",
"path": "/metrics",
"port": "9568"
}
},
"databaseRead": {
"password": "%s",
"username": "%s",
"createSchema": true,
"port": "%s",
"schema": "mdm_service",
"address": "%s",
"database": "%s"
},
"databaseWrite": {
"password": "%s",
"username": "%s",
"createSchema": true,
"port": "%s",
"schema": "mdm_service",
"address": "%s",
"database": "%s"
},
"externalIdListLimit": 10000
}', current_setting('rabbit.user'),
current_setting('rabbit.host'),
current_setting('rabbit.port'),
current_setting('rabbit.password'),
current_setting('migrationRead.db_pass'),
current_setting('migrationRead.db_user'),
current_setting('migrationRead.db_port'),
current_setting('migrationRead.db_host'),
current_setting('migrationRead.db_dbname'),
current_setting('migrationWrite.db_pass'),
current_setting('migrationWrite.db_user'),
current_setting('migrationWrite.db_port'),
current_setting('migrationWrite.db_host'),
current_setting('migrationWrite.db_dbname')
)) :: jsonb));
-- +goose Down
@@ -0,0 +1,73 @@
-- +goose Up
set migration.nats_host = 'isp-nats';
set migration.nats_port = '4223';
set migration.nats_cluster_id = 'test-cluster';
set migration.rabbit_host = 'isp-rabbit';
set migration.rabbit_port = '5672';
set migration.rabbit_user = 'guest';
set migration.rabbit_password = 'guest';
set migration.rabbit_system_queue_prefix = 'isp-test';
WITH moduleVar AS (
INSERT INTO modules (instance_id, name, active) VALUES (1, 'mdm-notify', 't') RETURNING id
)
INSERT INTO configs (module_id, active, data) VALUES (
(SELECT id FROM moduleVar),
't',
('{
"notifyConfigurations":[],
"logRabbitEnabled": false,
"logger": {
"asyncLogger":{
"enable": false,
"nats": {
"address": {
"port": "' || current_setting('migration.nats_port') || '",
"ip": "' || current_setting('migration.nats_host') || '"
},
"clusterId": "' || current_setting('migration.nats_cluster_id') || '"
}
},
"syncLogger": {
"enable": false,
"filename": "/opt/isp/isp-mdm-notify-service/events_logs/events.log"
},
"sendAddRequestSudirV1IsOn": true,
"sendFindRequestSudirV1IsOn": true,
"sendUpdateRequestSudirV1IsOn": true,
"sendUpdateRequestSudirV2IsOn": true,
"creatingSystemNotificationsIsOn": true,
"sendErlRequestQueueIsOn": true,
"sendJsonRequestQueueIsOn": true
},
"metrics":{
"gc": true,
"memory": true,
"address": {
"port": "9572",
"ip": "0.0.0.0",
"path": "/metrics"
}
},
"rabbit": {
"routingKey": "notification",
"exchangeName": "notifications",
"systemQueuesPrefix": "' || current_setting('migration.rabbit_system_queue_prefix') || '",
"declareQueueAndExchange": true,
"password": "' || current_setting('migration.rabbit_password') || '",
"user": "' || current_setting('migration.rabbit_user') || '",
"address": {
"ip": "' || current_setting('migration.rabbit_host') || '",
"port": "' || current_setting('migration.rabbit_port') || '"
},
"queue": {
"name": "notifier.queue",
"prefetchCount": 1000
}
}
}')::jsonb);
-- +goose Down
@@ -0,0 +1,117 @@
-- +goose Up
WITH moduleVar AS (
INSERT INTO modules (instance_id, name, active) VALUES (1, 'mdm-converter', 't') RETURNING id
)
INSERT INTO configs (module_id, active, data) VALUES (
(SELECT id FROM moduleVar),
't',
('{
"rules": {
"1": {
"availableFields": [
"*"
],
"formatting": {
"sudir_v1": {
"birth_dt": "dateFormatter",
"documents.1000016.start_dt": "dateFormatter"
},
"sudir_v2": {
"birth_dt": "dateFormatter",
"documents.1000016.start_dt": "dateFormatter"
},
"sudir_v1_find": {
"documents.1000016.start_dt": "dateFormatter",
"birth_dt": "dateFormatter"
},
"sudir_v2_find": {
"birth_dt": "dateFormatter",
"documents.1000016.start_dt": "dateFormatter"
}
},
"defaultValues": {
"sma": {
"*": "%undefined%"
}
}
},
"9": {
"availableFields": [
"*"
]
},
"10": {
"availableFields": [
"*"
]
}
},
"metrics": {
"address": {
"ip": "0.0.0.0",
"path": "/metrics",
"port": "9571"
},
"gc": true,
"memory": true
},
"formatters": {
"dateFormatter": {
"type": "DATE_TIME",
"outFormat": "2006-01-02",
"inputFormat": "2006-01-02 15:04:05.999"
}
},
"mappingSchema": {
"sudir_v2_find": {
"type": "sudir",
"extends": [
"sudir_v2"
]
},
"erl": {
"extends": [],
"mapping": {}
},
"sma": {
"mapping": {
}
},
"sudir": {
"type": "sudir",
"mapping": {
}
},
"sudir_v1": {
"type": "sudir",
"extends": [
"sudir"
],
"mapping": {}
},
"sudir_v2": {
"type": "sudir",
"extends": [
"sudir"
],
"mapping": {}
},
"sudir_v1_find": {
"type": "sudir",
"extends": [
"sudir_v1"
]
},
"test_protocol": {
"mapping": {
"etalon_id": "id"
}
}
}
}
'
)::jsonb);
-- +goose Down
@@ -0,0 +1,84 @@
-- +goose Up
set migration.nats_host = 'isp-nats';
set migration.nats_port = '4223';
set migration.nats_cluster_id = 'test-cluster';
set migration.rabbit_host = 'isp-rabbit';
set migration.rabbit_port = '5672';
set migration.rabbit_user = 'guest';
set migration.rabbit_password = 'guest';
WITH moduleVar AS (
INSERT INTO modules (instance_id, name, active) VALUES (1, 'mdm-adapter', 't') RETURNING id
)
INSERT INTO configs (module_id, active, data) VALUES (
(SELECT id FROM moduleVar),
't',
('{
"currentMode": "default",
"syncLogger": {
"filename": "/opt/isp/isp-mdm-adapter-service/events/events.log",
"enable": true
},
"asyncLogger": {
"enable": false,
"nats": {
"clusterId": "' || current_setting('migration.nats_cluster_id') || '",
"address": {
"ip": "' || current_setting('migration.nats_host') || '",
"port": "' || current_setting('migration.nats_port') || '"
}
}
},
"queue": {
"init": {
"concurrentConsumers": 1,
"name": "init",
"prefetchCount": 1000
},
"tempQueue": {
"name": "tempt",
"prefetchCount": 1000,
"concurrentConsumers": 1
},
"defaultQueue": {
"concurrentConsumers": 1,
"name": "events",
"prefetchCount": 1000
}
},
"rabbit": {
"password": "' || current_setting('migration.rabbit_password') || '",
"user": "' || current_setting('migration.rabbit_user') || '",
"address": {
"ip": "' || current_setting('migration.rabbit_host') || '",
"port": "' || current_setting('migration.rabbit_port') || '"
}
},
"metrics": {
"memory": true,
"address": {
"path": "/metrics",
"port": "9569",
"ip": "0.0.0.0"
},
"gc": true
},
"outputQueue": {
"routingKey": "external",
"enable": false,
"rabbit": {
"password": "' || current_setting('migration.rabbit_password') || '",
"user": "' || current_setting('migration.rabbit_user') || '",
"address": {
"ip": "' || current_setting('migration.rabbit_host') || '",
"port": "' || current_setting('migration.rabbit_port') || '"
}
},
"exchange": "external"
}
}')::jsonb);
-- +goose Down
@@ -0,0 +1,37 @@
-- +goose Up
WITH moduleVar AS (
INSERT INTO modules (instance_id, name, active) VALUES (1, 'mdm-api', 't') RETURNING id
)
INSERT INTO configs (module_id, active, data) VALUES (
(SELECT id FROM moduleVar),
't',
('{
"metrics": {
"memory": true,
"address": {
"path": "/metrics",
"port": "9570",
"ip": "0.0.0.0"
},
"gc": true
},
"outputQueue": {
"routingKey": "external",
"enable": false,
"exchange": "external"
},
"appConfigurations": [],
"limits": {
"defaultRecordsLimit": 1000,
"defaultPackageSizeLimit": 1000,
"defaultAsyncWorkersLimit": 2
},
"syncLogger": {
"enable": false,
"filename": "/opt/isp/isp-mdm-api-service/events/events.log.gz"
}
}')::jsonb);
-- +goose Down
@@ -0,0 +1,53 @@
-- +goose Up
set "rabbit.host" = 'isp-rabbit';
set "rabbit.port" = '5672';
set "rabbit.user" = 'guest';
set "rabbit.password" = 'guest';
set elastic.url = 'http://isp-elastic:9200';
WITH moduleVar AS (
INSERT INTO modules (instance_id, name, active) VALUES (1, 'mdm-search', 't') RETURNING id
)
INSERT INTO configs (module_id, active, data) VALUES (
(SELECT id FROM moduleVar),
't',
((format('{
"queue": {
"prefetchSize": 1000,
"searcherQueue": "searcher.queue",
"concurrentConsumers": 4
},
"rabbit": {
"user": "%s",
"address": {
"ip": "%s",
"port": "%s"
},
"password": "%s"
},
"elastic": {
"uRL": "%s",
"shards": 1
},
"metrics": {
"address": {
"ip": "0.0.0.0",
"path": "/metrics",
"port": "9573"
},
"gc": true,
"memory": true
},
"elasticDynamicDateFormats": ["yyyy-MM-dd HH:mm:ss.SSS"]
}', current_setting('rabbit.user'),
current_setting('rabbit.host'),
current_setting('rabbit.port'),
current_setting('rabbit.password'),
current_setting('elastic.url')
)) :: jsonb));
-- +goose Down
@@ -0,0 +1,72 @@
-- +goose Up
set migration.ds_db_host = 'isp-pgsql';
set migration.ds_db_port = '5432';
set migration.ds_db_dbname = 'isp-test';
set migration.ds_db_user = 'isp-test';
set migration.ds_db_pass = '123321';
set migration.internal_db_host = 'isp-pgsql';
set migration.internal_db_port = '5432';
set migration.internal_db_dbname = 'isp-test';
set migration.internal_db_user = 'isp-test';
set migration.internal_db_pass = '123321';
WITH moduleVar AS (
INSERT INTO modules (instance_id, name, active) VALUES (1, 'mdm-dumper', 't') RETURNING id
)
INSERT INTO configs (module_id, active, data) VALUES (
(SELECT id FROM moduleVar),
't',
((format('{
"limits": {
"rowsInFile": 1000000,
"fetchBatchSize": 1000,
"convertBatchSize": 300
},
"metrics": {
"gc": true,
"memory": true,
"address": {
"port": "9575",
"ip": "0.0.0.0",
"path": "/metrics"
}
},
"dataSourceDb": {
"password": "%s",
"username": "%s",
"createSchema": false,
"port": "%s",
"schema": "mdm_service",
"address": "%s",
"database": "%s"
},
"internalDb": {
"password": "%s",
"username": "%s",
"createSchema": true,
"port": "%s",
"schema": "mdm_dumper_service",
"address": "%s",
"database": "%s"
},
"schedules": [],
"workerCount": 1,
"dumpDirectoryPath": "/opt/msp/msp-mdm-dumper-service/dump"
}', current_setting('migration.ds_db_pass'),
current_setting('migration.ds_db_user'),
current_setting('migration.ds_db_port'),
current_setting('migration.ds_db_host'),
current_setting('migration.ds_db_dbname'),
current_setting('migration.internal_db_pass'),
current_setting('migration.internal_db_user'),
current_setting('migration.internal_db_port'),
current_setting('migration.internal_db_host'),
current_setting('migration.internal_db_dbname')
)) :: jsonb));
-- +goose Down
@@ -0,0 +1,55 @@
-- +goose Up
set migration.internal_db_host = 'isp-pgsql';
set migration.internal_db_port = '5432';
set migration.internal_db_dbname = 'isp-test';
set migration.internal_db_user = 'isp-test';
set migration.internal_db_pass = '123321';
WITH moduleVar AS (
INSERT INTO modules (instance_id, name, active) VALUES (1, 'mdm-async-api', 't') RETURNING id
)
INSERT INTO configs (module_id, active, data) VALUES (
(SELECT id FROM moduleVar),
't',
((format('{
"limits": {
"totalWorkers": 4,
"jobExecutionAttempts": 1
},
"metrics": {
"address": {
"ip": "0.0.0.0",
"path": "/metrics",
"port": "9576"
},
"gc": true,
"memory": true
},
"database": {
"password": "%s",
"username": "%s",
"createSchema": true,
"port": "%s",
"schema": "mdm_async_api_service",
"address": "%s",
"database": "%s"
},
"execution": {
"acquiredJobTTLInSec": 300,
"storeEntriesTTLInSec": 1800,
"purgeStoreTimeoutInSec": 600,
"jobStealingRequestTimeoutInSec": 5,
"scrollTTLInSec": 60
}
}',
current_setting('migration.internal_db_pass'),
current_setting('migration.internal_db_user'),
current_setting('migration.internal_db_port'),
current_setting('migration.internal_db_host'),
current_setting('migration.internal_db_dbname')
)) :: jsonb));
-- +goose Down
@@ -0,0 +1,20 @@
-- +goose Up
WITH moduleVar AS (
INSERT INTO modules (instance_id, name, active) VALUES (1, 'script', 't') RETURNING id
)
INSERT INTO configs (module_id, active, data) VALUES (
(SELECT id FROM moduleVar),
't',
('{
"scripts": [
],
"shaderScript": "",
"scriptExecutionTimeoutMs": 1000
}')::jsonb
);
-- +goose Down
-22
View File
@@ -1,22 +0,0 @@
package model
import (
"github.com/integration-system/isp-lib/database"
log "github.com/integration-system/isp-log"
"github.com/integration-system/isp-log/stdcodes"
)
var (
DbClient = database.NewRxDbClient(
database.WithSchemaEnsuring(),
database.WithSchemaAutoInjecting(),
database.WithMigrationsEnsuring(),
database.WithInitializingErrorHandler(func(err *database.ErrorEvent) {
log.Fatal(stdcodes.InitializingDbError, err.Error())
}),
)
ConfigRep ConfigRepository = &configRepPg{rxClient: DbClient}
CommonConfigRep CommonConfigRepository = &commonConfigRepPg{rxClient: DbClient}
SchemaRep SchemaRepository = &schemaRepPg{rxClient: DbClient}
ModuleRep ModulesRepository = &modulesRepPg{rxClient: DbClient}
)
-54
View File
@@ -1,54 +0,0 @@
package model
import (
"github.com/go-pg/pg"
"github.com/integration-system/isp-lib/database"
"isp-config-service/entity"
)
type CommonConfigRepository interface {
Snapshot() ([]entity.CommonConfig, error)
Upsert(config entity.CommonConfig) (*entity.CommonConfig, error)
Delete(identities []string) (int, error)
}
type commonConfigRepPg struct {
rxClient *database.RxDbClient
}
func (r *commonConfigRepPg) Snapshot() ([]entity.CommonConfig, error) {
configs := make([]entity.CommonConfig, 0)
err := r.rxClient.Visit(func(db *pg.DB) error {
return db.Model(&configs).Select()
})
return configs, err
}
func (r *commonConfigRepPg) Upsert(config entity.CommonConfig) (*entity.CommonConfig, error) {
err := r.rxClient.Visit(func(db *pg.DB) error {
_, err := db.Model(&config).
OnConflict("(id) DO UPDATE").
Returning("*").
Insert()
return err
})
if err != nil {
return nil, err
}
return &config, err
}
func (r *commonConfigRepPg) Delete(identities []string) (int, error) {
var err error
var res pg.Result
err = r.rxClient.Visit(func(db *pg.DB) error {
res, err = db.Model(&entity.CommonConfig{}).
Where("id IN (?)", pg.In(identities)).
Delete()
return err
})
if err != nil {
return 0, err
}
return res.RowsAffected(), err
}
+78 -36
View File
@@ -1,54 +1,96 @@
package model
import (
"github.com/go-pg/pg"
"github.com/integration-system/isp-lib/database"
"isp-config-service/entity"
"github.com/go-pg/pg"
"github.com/go-pg/pg/orm"
)
type ConfigRepository interface {
Snapshot() ([]entity.Config, error)
Upsert(config entity.Config) (*entity.Config, error)
Delete(identities []string) (int, error)
type ConfigRepository struct {
DB orm.DB
}
type configRepPg struct {
rxClient *database.RxDbClient
}
func (r *configRepPg) Snapshot() ([]entity.Config, error) {
configs := make([]entity.Config, 0)
err := r.rxClient.Visit(func(db *pg.DB) error {
return db.Model(&configs).Select()
})
func (r *ConfigRepository) GetConfigs(identities []int64) ([]entity.Config, error) {
var configs []entity.Config
var err error
if len(identities) > 0 {
err = r.DB.Model(&configs).
Where("id IN (?)", pg.In(identities)).
Order("created_at DESC").
Limit(500).
Select()
} else {
err = r.DB.Model(&configs).
Order("created_at DESC").
Limit(500).
Select()
}
return configs, err
}
func (r *configRepPg) Upsert(config entity.Config) (*entity.Config, error) {
err := r.rxClient.Visit(func(db *pg.DB) error {
_, err := db.Model(&config).
OnConflict("(id) DO UPDATE").
Returning("*").
Insert()
return err
})
func (r *ConfigRepository) GetConfigsByModulesId(modulesId []int32) ([]entity.Config, error) {
var res []entity.Config
err := r.DB.Model(&res).Where("module_id IN (?)", pg.In(modulesId)).Order("created_at DESC").Select()
if err != nil {
return nil, err
}
return &config, err
return res, nil
}
func (r *configRepPg) Delete(identities []string) (int, error) {
var err error
var res pg.Result
err = r.rxClient.Visit(func(db *pg.DB) error {
res, err = db.Model(&entity.Config{}).
Where("id IN (?)", pg.In(identities)).
Delete()
return err
})
if err != nil {
return 0, err
func (r *ConfigRepository) CreateConfig(config *entity.Config) (*entity.Config, error) {
_, err := r.DB.Model(config).
Returning("*").
Insert()
return config, err
}
func (r *ConfigRepository) UpdateConfig(config *entity.Config) (*entity.Config, error) {
_, err := r.DB.Model(config).WherePK().
Returning("*").
Update()
return config, err
}
func (r *ConfigRepository) DeleteConfig(identities []int64) (int, error) {
result, err := r.DB.Exec("DELETE FROM "+schema+".configs WHERE id IN (?)", pg.In(identities))
return result.RowsAffected(), err
}
func (r *ConfigRepository) GetConfigById(identity int64) (*entity.Config, error) {
cfg := new(entity.Config)
err := r.DB.Model(cfg).
Where("id = ?", identity).
First()
if err == pg.ErrNoRows {
return nil, nil
}
return res.RowsAffected(), err
return cfg, err
}
func (r *ConfigRepository) GetConfigByInstanceUUIDAndModuleName(instanceUUID string, moduleName string) (*entity.Config, error) {
cfg := new(entity.Config)
err := r.DB.Model(cfg).
Where(`module_id = (SELECT id FROM `+schema+`.modules WHERE name = ?
AND instance_id = (SELECT id FROM `+schema+`.instances WHERE uuid = ?))`, moduleName, instanceUUID).
Where("active = true").
Order("updated_at DESC").
First()
if err == pg.ErrNoRows {
return nil, nil
}
return cfg, err
}
func (r *ConfigRepository) GetModuleNameAndInstanceUUIDByConfigId(configId int64) (entity.ModuleInstanceIdentity, error) {
var cfg entity.ModuleInstanceIdentity
_, err := r.DB.Query(&cfg, `SELECT temp.name, uuid
FROM (SELECT name, instance_id FROM `+schema+`.modules WHERE id =
(SELECT module_id FROM `+schema+`.configs WHERE id = ? AND active = true)) temp
LEFT JOIN `+schema+`.instances s ON s.id = temp.instance_id`, configId)
if err != nil && err == pg.ErrNoRows {
return cfg, nil
}
return cfg, err
}
+73
View File
@@ -0,0 +1,73 @@
package model
import (
"isp-config-service/entity"
"github.com/go-pg/pg"
"github.com/go-pg/pg/orm"
)
type InstanceRepository struct {
DB orm.DB
}
func (r *InstanceRepository) GetInstances(identities []int32) ([]entity.Instance, error) {
var instances []entity.Instance
var err error
if len(identities) > 0 {
err = r.DB.Model(&instances).
Where("id IN (?)", pg.In(identities)).
Order("created_at DESC").
Limit(500).
Select()
} else {
err = r.DB.Model(&instances).
Order("created_at DESC").
Limit(500).
Select()
}
return instances, err
}
func (r *InstanceRepository) CreateInstance(instance entity.Instance) (entity.Instance, error) {
_, err := r.DB.Model(&instance).
Returning("id").
Returning("created_at").
Insert()
return instance, err
}
func (r *InstanceRepository) UpdateInstance(instance entity.Instance) (entity.Instance, error) {
_, err := r.DB.Model(&instance).WherePK().
Returning("id").
Returning("created_at").
Update()
return instance, err
}
func (r *InstanceRepository) DeleteInstance(identities []int32) (int, error) {
result, err := r.DB.Exec("DELETE FROM "+schema+".instances WHERE id IN (?)", pg.In(identities))
return result.RowsAffected(), err
}
func (r *InstanceRepository) GetInstanceById(identity int32) (entity.Instance, error) {
var module entity.Instance
err := r.DB.Model(&module).
Where("id = ?", identity).
First()
if err != nil && err == pg.ErrNoRows {
return module, nil
}
return module, err
}
func (r *InstanceRepository) GetInstanceByUuid(instanceUuid string) (entity.Instance, error) {
var instance entity.Instance
err := r.DB.Model(&instance).
Where("uuid = ?", instanceUuid).
First()
if err != nil && err == pg.ErrNoRows {
return instance, nil
}
return instance, err
}
+123 -35
View File
@@ -1,53 +1,141 @@
package model
import (
"github.com/go-pg/pg"
"github.com/integration-system/isp-lib/database"
"isp-config-service/entity"
"github.com/go-pg/pg"
"github.com/go-pg/pg/orm"
"time"
)
type ModulesRepository interface {
Snapshot() ([]entity.Module, error)
Upsert(module entity.Module) (*entity.Module, error)
Delete(identities []string) (int, error)
type ModulesRepository struct {
DB orm.DB
}
type modulesRepPg struct {
rxClient *database.RxDbClient
}
func (r *modulesRepPg) Snapshot() ([]entity.Module, error) {
modules := make([]entity.Module, 0)
err := r.rxClient.Visit(func(db *pg.DB) error {
return db.Model(&modules).Select()
})
func (r *ModulesRepository) GetModules(identities []int32) ([]entity.Module, error) {
var modules []entity.Module
var err error
if len(identities) > 0 {
err = r.DB.Model(&modules).
Where("id IN (?)", pg.In(identities)).
Order("created_at DESC").
Limit(500).
Select()
} else {
err = r.DB.Model(&modules).
Order("created_at DESC").
Limit(500).
Select()
}
return modules, err
}
func (r *modulesRepPg) Upsert(module entity.Module) (*entity.Module, error) {
err := r.rxClient.Visit(func(db *pg.DB) error {
_, err := db.Model(&module).
OnConflict("(id) DO UPDATE").
Returning("*").
Insert()
return err
})
if err != nil {
return nil, err
}
func (r *ModulesRepository) GetModule(identity int32) (*entity.Module, error) {
var module entity.Module
var err = r.DB.Model(&module).Where("id = ?", identity).Select()
return &module, err
}
func (r *modulesRepPg) Delete(identities []string) (int, error) {
var err error
var res pg.Result
err = r.rxClient.Visit(func(db *pg.DB) error {
res, err = db.Model(&entity.Module{}).
Where("id IN (?)", pg.In(identities)).Delete()
func (r *ModulesRepository) GetActiveModules() ([]entity.Module, error) {
var modules []entity.Module
err := r.DB.Model(&modules).
Order("created_at DESC").
Where("active = true").
Limit(500).
Select()
return modules, err
}
func (r *ModulesRepository) CreateModule(module entity.Module) (entity.Module, error) {
_, err := r.DB.Model(&module).
Returning("id").
Returning("active").
Returning("created_at").
Insert()
return module, err
}
func (r *ModulesRepository) UpdateModule(module entity.Module) (entity.Module, error) {
_, err := r.DB.Model(&module).WherePK().
Returning("id").
Returning("active").
Returning("created_at").
Update()
return module, err
}
func (r *ModulesRepository) DeleteModule(identities []int32) (int, error) {
result, err := r.DB.Exec("DELETE FROM "+schema+".modules WHERE id IN (?)", pg.In(identities))
return result.RowsAffected(), err
}
func (r *ModulesRepository) GetModuleById(identity int32) (entity.Module, error) {
var module entity.Module
err := r.DB.Model(&module).
Where("id = ?", identity).
First()
if err != nil && err == pg.ErrNoRows {
return module, nil
}
return module, err
}
func (r *ModulesRepository) GetModuleByInstanceIdAndName(instanceId int32, moduleName string) (entity.Module, error) {
var module entity.Module
err := r.DB.Model(&module).
Where("name = ?", moduleName).
Where("instance_id = ?", instanceId).
First()
if err == pg.ErrNoRows {
return module, nil
}
return module, err
}
func (r *ModulesRepository) UpdateModuleDisconnect(instanceUuid string, moduleName string) error {
var module entity.Module
err := r.DB.Model(&module).
Where("name = ?", moduleName).
Where("instance_id = (SELECT id FROM "+schema+".instances WHERE uuid = ?)", instanceUuid).
First()
if err != nil {
return err
})
}
if module.Id != 0 {
module.LastDisconnectedAt = time.Now()
_, err := r.DB.Model(&module).WherePK().Update()
if err != nil {
return err
}
}
return err
}
func (r *ModulesRepository) GetModulesByInstanceUuid(instanceUuid string) ([]entity.Module, error) {
var res []entity.Module
err := r.DB.Model(&res).
Where("instance_id = (SELECT id FROM "+schema+".instances WHERE uuid = ?)", instanceUuid).
Select()
if err != nil {
return nil, err
}
return res, nil
}
func (r *ModulesRepository) GetModulesByInstanceUuidAndName(instanceUuid string, name string) (*entity.Module, error) {
res := new(entity.Module)
err := r.DB.Model(res).
Where("instance_id = (SELECT id FROM "+schema+".instances WHERE uuid = ?)", instanceUuid).
Where("name = ?", name).
First()
if err == pg.ErrNoRows {
return nil, nil
}
if err != nil {
return 0, err
return nil, err
}
return res.RowsAffected(), err
return res, nil
}
+24
View File
@@ -0,0 +1,24 @@
package model
import (
"github.com/go-pg/pg"
)
var (
schema = ""
ConfigRep ConfigRepository
ModulesRep ModulesRepository
InstanceRep InstanceRepository
SchemaRep SchemaRepository
)
func SetSchema(s string) {
schema = s
}
func InitDbManager(db *pg.DB) {
ConfigRep = ConfigRepository{db}
ModulesRep = ModulesRepository{db}
InstanceRep = InstanceRepository{db}
SchemaRep = SchemaRepository{db}
}
+23 -33
View File
@@ -2,52 +2,42 @@ package model
import (
"github.com/go-pg/pg"
"github.com/integration-system/isp-lib/database"
"github.com/go-pg/pg/orm"
"isp-config-service/entity"
)
type SchemaRepository interface {
Snapshot() ([]entity.ConfigSchema, error)
Upsert(schema entity.ConfigSchema) (*entity.ConfigSchema, error)
Delete(identities []string) (int, error)
type SchemaRepository struct {
DB orm.DB
}
type schemaRepPg struct {
rxClient *database.RxDbClient
func (r *SchemaRepository) InsertConfigSchema(s *entity.ConfigSchema) (*entity.ConfigSchema, error) {
_, err := r.DB.Model(s).Returning("*").Insert()
return s, err
}
func (r *schemaRepPg) Snapshot() ([]entity.ConfigSchema, error) {
schemas := make([]entity.ConfigSchema, 0)
err := r.rxClient.Visit(func(db *pg.DB) error {
return db.Model(&schemas).Select()
})
return schemas, err
func (r *SchemaRepository) UpdateConfigSchema(s *entity.ConfigSchema) (*entity.ConfigSchema, error) {
_, err := r.DB.Model(s).Returning("*").WherePK().Update()
return s, err
}
func (r *schemaRepPg) Upsert(schema entity.ConfigSchema) (*entity.ConfigSchema, error) {
err := r.rxClient.Visit(func(db *pg.DB) error {
_, err := db.Model(&schema).
OnConflict("(id) DO UPDATE").
Returning("*").
Insert()
return err
})
func (r *SchemaRepository) GetSchemasByModulesId(modulesId []int32) ([]entity.ConfigSchema, error) {
var res []entity.ConfigSchema
err := r.DB.Model(&res).Where("module_id IN (?)", pg.In(modulesId)).Select()
if err != nil {
return nil, err
}
return &schema, err
return res, nil
}
func (r *schemaRepPg) Delete(identities []string) (int, error) {
var err error
var res pg.Result
err = r.rxClient.Visit(func(db *pg.DB) error {
res, err = db.Model(&entity.ConfigSchema{}).
Where("id IN (?)", pg.In(identities)).Delete()
return err
})
if err != nil {
return 0, err
func (r *SchemaRepository) GetSchemaByModuleId(moduleId int32) (*entity.ConfigSchema, error) {
var model entity.ConfigSchema
if err := r.DB.Model(&model).Where("module_id = ?", moduleId).Select(); err != nil {
if err == pg.ErrNoRows {
return nil, nil
} else {
return nil, err
}
} else {
return &model, nil
}
return res.RowsAffected(), err
}
+134
View File
@@ -0,0 +1,134 @@
package module
import (
"github.com/integration-system/isp-lib/config"
"isp-config-service/conf"
"isp-config-service/domain"
st "isp-config-service/entity"
"isp-config-service/model"
"isp-config-service/socket"
"sort"
"time"
)
var (
startAt = time.Now()
Version = "0.1.0"
)
func GetAggregatedModuleInfo(instanceUuid string) ([]*domain.ModuleInfo, error) {
modules, err := model.ModulesRep.GetModulesByInstanceUuid(instanceUuid)
if err != nil {
return nil, err
}
config := config.Get().(*conf.Configuration)
modules = append(modules, st.Module{
Id: -1,
Name: config.ModuleName,
Active: true,
CreatedAt: startAt,
InstanceId: -1,
})
l := len(modules)
res := make([]*domain.ModuleInfo, l)
m := make(map[int32]*domain.ModuleInfo, l)
idList := make([]int32, l)
for i, module := range modules {
idList[i] = module.Id
info := &domain.ModuleInfo{
Id: module.Id,
Name: module.Name,
Active: module.Active,
CreatedAt: module.CreatedAt,
LastConnectedAt: module.LastConnectedAt,
LastDisconnectedAt: module.LastDisconnectedAt,
}
m[module.Id] = info
res[i] = info
}
configs, err := model.ConfigRep.GetConfigsByModulesId(idList)
if err != nil {
return nil, err
}
for _, cfg := range configs {
info := m[cfg.ModuleId]
info.Configs = append(info.Configs, cfg)
}
schemas, err := model.SchemaRep.GetSchemasByModulesId(idList)
if err != nil {
return nil, err
}
for _, s := range schemas {
info := m[s.ModuleId]
schema := s.Schema
info.ConfigSchema = &schema
}
connMap := socket.GetModuleConnectionIdMapByInstanceId(instanceUuid)
routes := socket.GetRoutes().Routes
//converters := socket.GetConverters()
//routers := socket.GetRouters()
roomsStat := socket.GetRoomsCount()
for _, info := range res {
if info.Id == -1 {
info.Status = append(info.Status, domain.Connection{
Address: config.GrpcOuterAddress,
Version: Version,
Endpoints: socket.ConfigServiceBackendDeclaration.Endpoints,
LibVersion: socket.ConfigServiceBackendDeclaration.LibVersion,
EstablishedAt: startAt,
})
} else if conns, connected := connMap[info.Name]; connected {
for _, conId := range conns {
hasRoutes := false
var data *domain.Connection
if backend, ok := routes[conId]; ok {
data = &domain.Connection{
Version: backend.Version,
LibVersion: backend.LibVersion,
Address: backend.Address,
Endpoints: backend.Endpoints,
}
hasRoutes = true
} else if roomsStat[instanceUuid][info.Name] <= 0 {
continue
}
if c, ok := socket.GetConnectionById(instanceUuid, conId); ok {
if !hasRoutes {
data = &domain.Connection{
Version: "unknown",
}
/*if router, ok := routers[conId]; ok {
data.Address = router
} else if converter, ok := converters[conId]; ok {
data.Address = converter
}*/
}
data.EstablishedAt = c.EstablishedAt
}
info.Status = append(info.Status, *data)
}
}
}
for _, s := range res {
sort.Slice(s.Status, func(i, j int) bool {
return s.Status[i].EstablishedAt.Before(s.Status[j].EstablishedAt)
})
for _, con := range s.Status {
sort.Slice(con.Endpoints, func(i, j int) bool {
return con.Endpoints[i].Path < con.Endpoints[j].Path
})
}
}
sort.Slice(res, func(i, j int) bool {
return res[i].Name < res[j].Name
})
return res, nil
}
-44
View File
@@ -1,44 +0,0 @@
package mux
import (
"bytes"
)
type Matcher func([]byte) bool
// Any is a Matcher that matches any connection.
func Any() Matcher {
return func(_ []byte) bool {
return true
}
}
var httpMethods = map[string]struct{}{
"OPTIONS": {},
"HEAD": {},
"GET": {},
"POST": {},
"PUT": {},
"PATCH": {},
"DELETE": {},
"TRACE": {},
"CONNECT": {},
}
// HTTP1 only matches the methods in the HTTP request.
func HTTP1() Matcher {
return func(data []byte) bool {
// max length of method
l := 7
if len(data) < l {
l = len(data)
}
methodB := data[:l]
words := bytes.Split(methodB, []byte(" "))
if len(words) == 0 {
return false
}
_, ok := httpMethods[string(words[0])]
return ok
}
}
-186
View File
@@ -1,186 +0,0 @@
package mux
import (
"errors"
"github.com/integration-system/isp-lib/atomic"
"net"
"sync"
)
var (
ErrListenerClosed = errors.New("mux: listener closed")
ErrNotMatched = errors.New("mux: connection not matched by a matcher")
)
type Mux interface {
Match(Matcher) net.Listener
Serve() error
OnError(func(error))
Close() error
}
type matchersListener struct {
matcher Matcher
listener *muxListener
}
type mux struct {
listener net.Listener
ml []matchersListener
connBufLen int
doneCh chan struct{}
errHandler func(error)
}
func (m *mux) Match(matcher Matcher) net.Listener {
ml := newMuxListener(m.listener, m.connBufLen)
m.ml = append(m.ml, matchersListener{matcher: matcher, listener: ml})
return ml
}
func (m *mux) Serve() error {
var wg sync.WaitGroup
defer func() {
close(m.doneCh)
wg.Wait()
for _, sl := range m.ml {
_ = sl.listener.Close()
for c := range sl.listener.connCh {
_ = c.Close()
}
close(sl.listener.connCh)
}
}()
for {
c, err := m.listener.Accept()
if err != nil {
if ne, ok := err.(net.Error); ok && ne.Temporary() {
continue
}
return err
}
wg.Add(1)
go m.serve(c, &wg)
}
}
func (m *mux) Close() error {
return m.listener.Close()
}
func (m *mux) OnError(f func(error)) {
m.errHandler = f
}
func (m *mux) serve(c net.Conn, wg *sync.WaitGroup) {
defer wg.Done()
buf := getBuffer()
n, err := c.Read(buf)
data := buf[:n]
for _, matcher := range m.ml {
matched := matcher.matcher(data)
if matched {
if matcher.listener.closed.Get() {
break
}
muc := newMuxConn(c, data, err)
select {
case matcher.listener.connCh <- muc:
case <-m.doneCh:
putBuffer(buf)
_ = c.Close()
}
return
}
}
putBuffer(buf)
_ = c.Close()
if m.errHandler != nil {
m.errHandler(ErrNotMatched)
}
}
func (m *mux) handleErr(err error) bool {
if ne, ok := err.(net.Error); ok {
return ne.Temporary()
}
return false
}
func New(l net.Listener) Mux {
return &mux{
listener: l,
connBufLen: 1024,
doneCh: make(chan struct{}),
}
}
type muxListener struct {
root net.Listener
connCh chan net.Conn
closed *atomic.AtomicBool
}
func (l *muxListener) Accept() (net.Conn, error) {
if l.closed.Get() {
return nil, ErrListenerClosed
}
c, ok := <-l.connCh
if !ok || l.closed.Get() {
return nil, ErrListenerClosed
}
return c, nil
}
// Close stops listening on address.
// Already Accepted connections are not closed.
func (l *muxListener) Close() error {
l.closed.Set(true)
return nil
}
func (l *muxListener) Addr() net.Addr {
return l.root.Addr()
}
func newMuxListener(root net.Listener, connBufLen int) *muxListener {
return &muxListener{
root: root,
connCh: make(chan net.Conn, connBufLen),
closed: atomic.NewAtomicBool(false),
}
}
type muxConn struct {
net.Conn
buf []byte
lastErr error
}
func newMuxConn(c net.Conn, buf []byte, lastErr error) *muxConn {
return &muxConn{
Conn: c,
buf: buf,
lastErr: lastErr,
}
}
func (m *muxConn) Read(p []byte) (int, error) {
if m.buf != nil {
n := copy(p, m.buf)
if len(m.buf) == n {
putBuffer(m.buf)
m.buf = nil
} else {
m.buf = m.buf[n:]
}
return n, m.lastErr
}
return m.Conn.Read(p)
}
-118
View File
@@ -1,118 +0,0 @@
package mux
import (
"fmt"
"github.com/stretchr/testify/assert"
"io/ioutil"
"log"
"net"
"net/http"
"net/http/httptest"
"testing"
"time"
)
func TestHTTP1(t *testing.T) {
a := assert.New(t)
path := "/test/"
method := "GET"
mockResData := []byte("948 res")
var responseData []byte
rootListener := newLocalListener()
mux := New(rootListener)
httpListener := mux.Match(HTTP1())
mux.OnError(func(err error) {
a.Fail("connection not matched by a http matcher")
})
go func() {
err := mux.Serve()
log.Println(err)
}()
handler := func(writer http.ResponseWriter, request *http.Request) {
var err error
a.Equal(method, request.Method)
n, err := writer.Write(mockResData)
a.NoError(err)
a.Len(mockResData, n)
}
httpMux := http.NewServeMux()
httpMux.HandleFunc(path, handler)
httpServer := httptest.NewUnstartedServer(httpMux)
httpServer.Listener = httpListener
httpServer.Start()
url := httpServer.URL + path
httpClient := httpServer.Client()
req, _ := http.NewRequest(method, url, nil)
res, err := httpClient.Do(req)
a.NoError(err)
if a.NotNil(res) {
a.Equal(200, res.StatusCode)
responseData, err = ioutil.ReadAll(res.Body)
}
time.Sleep(10 * time.Millisecond)
a.Equal(mockResData, responseData)
}
func TestAny(t *testing.T) {
a := assert.New(t)
mockReqData := []byte("1 somre")
requestData := make([]byte, len(mockReqData))
rootListener := newLocalListener()
mux := New(rootListener)
httpListener := mux.Match(HTTP1())
tcpListener := mux.Match(Any())
go func() {
err := mux.Serve()
log.Println(err)
}()
handler := func(writer http.ResponseWriter, request *http.Request) {
a.Fail("matched http handler")
}
httpMux := http.NewServeMux()
httpMux.HandleFunc("/", handler)
httpServer := httptest.NewUnstartedServer(httpMux)
httpServer.Listener = httpListener
httpServer.Start()
hadTcpConn := false
go func() {
for {
conn, err := tcpListener.Accept()
if hadTcpConn {
a.Fail("more than one tcp conn")
return
}
hadTcpConn = true
a.NoError(err)
_, err = conn.Read(requestData)
a.NoError(err)
a.Equal(mockReqData, requestData)
}
}()
tcpAddr := tcpListener.Addr().String()
conn, err := net.Dial("tcp", tcpAddr)
a.NoError(err)
n, err := conn.Write(mockReqData)
a.Len(mockReqData, n)
a.NoError(err)
time.Sleep(10 * time.Millisecond)
a.Equal(mockReqData, requestData)
a.True(hadTcpConn)
}
func newLocalListener() net.Listener {
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
panic(fmt.Sprintf("failed to listen on a port: %v", err))
}
return l
}
-22
View File
@@ -1,22 +0,0 @@
package mux
import (
"sync"
)
// could be increased if needed for new matchers
const bufferSize = 10
var pool sync.Pool
func getBuffer() []byte {
b, ok := pool.Get().([]byte)
if !ok {
b = make([]byte, bufferSize)
}
return b
}
func putBuffer(b []byte) {
pool.Put(b[:cap(b)])
}
+28
View File
@@ -0,0 +1,28 @@
syntax = "proto3";
// /home/andrey/Applications/protoc/bin/protoc -I ./ proto/system.proto --go_out=plugins=grpc:./
option java_multiple_files = true;
option java_package = "io.grpc.convertService";
option java_outer_classname = "ConvertServiceProto";
package isp;
import "google/api/annotations.proto";
import "google/protobuf/struct.proto";
message Message {
oneof body {
google.protobuf.Struct structBody = 1;
google.protobuf.ListValue listBody = 2;
google.protobuf.NullValue NullBody = 3;
}
}
service BackendService {
// ===== SYSTEM =====
rpc Request (Message) returns (Message) {
option (google.api.http) = {
post: "/api"
body: "*"
};
}
}
+134
View File
@@ -0,0 +1,134 @@
{
"swagger": "2.0",
"info": {
"title": "proto/backend_service.proto",
"version": "version not set"
},
"schemes": [
"http",
"https"
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"paths": {
"/api": {
"post": {
"summary": "===== SYSTEM =====",
"operationId": "Request",
"responses": {
"200": {
"description": "",
"schema": {
"$ref": "#/definitions/ispMessage"
}
}
},
"parameters": [
{
"name": "Grpc-Metadata-proxy_method_name",
"in": "header",
"required": true,
"type": "string"
},
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/ispMessage"
}
}
],
"tags": [
"BackendService"
]
}
}
},
"definitions": {
"ispMessage": {
"type": "object",
"properties": {
"structBody": {
"$ref": "#/definitions/protobufStruct"
},
"listBody": {
"$ref": "#/definitions/protobufListValue"
},
"NullBody": {
"$ref": "#/definitions/protobufNullValue"
}
}
},
"protobufListValue": {
"type": "object",
"properties": {
"values": {
"type": "array",
"items": {
"$ref": "#/definitions/protobufValue"
},
"description": "Repeated field of dynamically typed values."
}
},
"description": "`ListValue` is a wrapper around a repeated field of values.\n\nThe JSON representation for `ListValue` is JSON array."
},
"protobufNullValue": {
"type": "string",
"enum": [
"NULL_VALUE"
],
"default": "NULL_VALUE",
"description": "`NullValue` is a singleton enumeration to represent the null value for the\n`Value` type union.\n\n The JSON representation for `NullValue` is JSON `null`.\n\n - NULL_VALUE: Null value."
},
"protobufStruct": {
"type": "object",
"properties": {
"fields": {
"type": "object",
"additionalProperties": {
"$ref": "#/definitions/protobufValue"
},
"description": "Unordered map of dynamically typed values."
}
},
"description": "`Struct` represents a structured data value, consisting of fields\nwhich map to dynamically typed values. In some languages, `Struct`\nmight be supported by a native representation. For example, in\nscripting languages like JS a struct is represented as an\nobject. The details of that representation are described together\nwith the proto support for the language.\n\nThe JSON representation for `Struct` is JSON object."
},
"protobufValue": {
"type": "object",
"properties": {
"null_value": {
"$ref": "#/definitions/protobufNullValue",
"description": "Represents a null value."
},
"number_value": {
"type": "number",
"format": "double",
"description": "Represents a double value."
},
"string_value": {
"type": "string",
"description": "Represents a string value."
},
"bool_value": {
"type": "boolean",
"format": "boolean",
"description": "Represents a boolean value."
},
"struct_value": {
"$ref": "#/definitions/protobufStruct",
"description": "Represents a structured value."
},
"list_value": {
"$ref": "#/definitions/protobufListValue",
"description": "Represents a repeated `Value`."
}
},
"description": "`Value` represents a dynamically typed value which can be either\nnull, a number, a string, a boolean, a recursive struct value, or a\nlist of values. A producer of value is expected to set one of that\nvariants, absence of any variant indicates an error.\n\nThe JSON representation for `Value` is JSON value."
}
}
}
+164
View File
@@ -0,0 +1,164 @@
syntax = "proto3";
// /home/andrey/Applications/protoc/bin/protoc -I ./ proto/system.proto --go_out=plugins=grpc:./
option java_multiple_files = true;
option java_package = "io.grpc.configService";
option java_outer_classname = "ConfigServiceProto";
package config.service;
import "google/api/annotations.proto";
import "google/protobuf/struct.proto";
service ConfigService {
// ===== INSTANCE =====
rpc GetInstances (RequestByIdentities) returns (InstancesResponse) {
option (google.api.http) = {
post: "/api/instances"
body: "*"
};
}
rpc CreateUpdateInstance (Instance) returns (Instance) {
option (google.api.http) = {
post: "/api/instances/save"
body: "*"
};
}
rpc DeleteInstance (RequestByIdentities) returns (DeleteResponse) {
option (google.api.http) = {
post: "/api/instances/delete"
body: "*"
};
}
// ===== INSTANCE END =====
// ===== MODULE =====
rpc GetModules (RequestByIdentities) returns (ModulesResponse) {
option (google.api.http) = {
post: "/api/modules"
body: "*"
};
}
rpc GetActiveModules (Empty) returns (ModulesResponse) {
option (google.api.http).get = "/api/modules/actives";
}
rpc CreateUpdateModule (Module) returns (Module) {
option (google.api.http) = {
post: "/api/modules/save"
body: "*"
};
}
rpc DeleteModule (RequestByIdentities) returns (DeleteResponse) {
option (google.api.http) = {
post: "/api/modules/delete"
body: "*"
};
}
rpc GetConnectedModules (Empty) returns (ConnectedModules) {
option (google.api.http).get = "/api/modules/connected";
}
// ===== MODULE END =====
// ===== CONFIG =====
rpc GetConfigs (RequestByIdentities) returns (ConfigsResponse) {
option (google.api.http) = {
post: "/api/configs"
body: "*"
};
}
rpc GetConfigByInstanceUUIDAndModuleName (RequestConfig) returns (Config) {
option (google.api.http).get = "/api/configs_by_module_names/{name}";
}
rpc CreateUpdateConfig (Config) returns (Config) {
option (google.api.http) = {
post: "/api/configs/save"
body: "*"
};
}
rpc DeleteConfig (RequestByIdentities) returns (DeleteResponse) {
option (google.api.http) = {
post: "/api/configs/delete"
body: "*"
};
}
rpc MarkConfigAsActive (RequestByLongIdentity) returns (Config) {
option (google.api.http) = {
post: "/api/configs/active"
body: "*"
};
}
// ===== CONFIG END =====
}
message RequestByLongIdentity {
int64 id = 1;
}
message RequestByIdentities {
repeated int32 ids = 1;
}
message RequestConfig {
string instanceUuid = 1;
string name = 2;
}
message ConnectedModules {
google.protobuf.Struct items = 1;
}
message Instance {
int32 id = 1;
string uuid = 2;
string name = 3;
string createdAt = 4;
}
message Module {
int32 id = 1;
int32 instanceId = 2;
string name = 3;
bool active = 4;
string createdAt = 5;
string lastConnectedAt = 6;
string lastDisconnectedAt = 7;
}
message Config {
int64 id = 1;
int32 moduleId = 2;
int32 version = 3;
bool active = 4;
string createdAt = 5;
string updatedAt = 6;
google.protobuf.Struct data = 7;
}
message InstancesResponse {
repeated Instance items = 1;
}
message ModulesResponse {
repeated Module items = 1;
}
message ConfigsResponse {
repeated Config items = 1;
}
message DeleteResponse {
int32 deleted = 1;
}
message Empty {
}
-105
View File
@@ -1,105 +0,0 @@
package raft
import (
"fmt"
"github.com/hashicorp/go-hclog"
isplog "github.com/integration-system/isp-log"
"github.com/sirupsen/logrus"
"github.com/spf13/cast"
"io"
"isp-config-service/codes"
"log"
)
type LoggerAdapter struct {
name string
}
func (l *LoggerAdapter) Log(level logrus.Level, msg string, args ...interface{}) {
if l.name != "" {
msg = fmt.Sprintf("%s:%s", l.name, msg)
}
if len(args) != 0 {
metadata := make(map[string]interface{}, len(args)/2)
for i := 0; i < len(args)-1; i += 2 {
k := cast.ToString(args[i])
metadata[k] = args[i+1]
}
isplog.WithMetadata(metadata).Log(level, codes.RaftLoggerCode, msg)
} else {
isplog.Log(level, codes.RaftLoggerCode, msg)
}
}
func (l *LoggerAdapter) Trace(msg string, args ...interface{}) {
l.Log(logrus.TraceLevel, msg, args...)
}
func (l *LoggerAdapter) Debug(msg string, args ...interface{}) {
l.Log(logrus.DebugLevel, msg, args...)
}
func (l *LoggerAdapter) Info(msg string, args ...interface{}) {
l.Log(logrus.InfoLevel, msg, args...)
}
func (l *LoggerAdapter) Warn(msg string, args ...interface{}) {
l.Log(logrus.WarnLevel, msg, args...)
}
func (l *LoggerAdapter) Error(msg string, args ...interface{}) {
l.Log(logrus.ErrorLevel, msg, args...)
}
func (l *LoggerAdapter) IsTrace() bool {
return isplog.IsLevelEnabled(logrus.TraceLevel)
}
func (l *LoggerAdapter) IsDebug() bool {
return isplog.IsLevelEnabled(logrus.DebugLevel)
}
func (l *LoggerAdapter) IsInfo() bool {
return isplog.IsLevelEnabled(logrus.InfoLevel)
}
func (l *LoggerAdapter) IsWarn() bool {
return isplog.IsLevelEnabled(logrus.WarnLevel)
}
func (l *LoggerAdapter) IsError() bool {
return isplog.IsLevelEnabled(logrus.ErrorLevel)
}
// No need to implement that as Raft doesn't use this method.
func (l *LoggerAdapter) With(args ...interface{}) hclog.Logger {
return l
}
func (l *LoggerAdapter) Named(name string) hclog.Logger {
sl := *l
if sl.name != "" {
sl.name = sl.name + "." + name
} else {
sl.name = name
}
return &sl
}
func (l *LoggerAdapter) ResetNamed(name string) hclog.Logger {
sl := *l
sl.name = name
return &sl
}
// Skip
func (l *LoggerAdapter) SetLevel(level hclog.Level) {
}
func (l *LoggerAdapter) StandardLogger(opts *hclog.StandardLoggerOptions) *log.Logger {
return log.New(isplog.GetOutput(), "", 0)
}
func (l *LoggerAdapter) StandardWriter(opts *hclog.StandardLoggerOptions) io.Writer {
return isplog.GetOutput()
}
-167
View File
@@ -1,167 +0,0 @@
package raft
import (
"github.com/hashicorp/raft"
raftboltdb "github.com/hashicorp/raft-boltdb"
"github.com/pkg/errors"
"isp-config-service/conf"
"net"
"os"
"path/filepath"
"time"
)
const (
defaultSyncTimeout = 3 * time.Second
dbFile = "raft_db"
)
type ChangeLeaderNotification struct {
IsLeader bool
CurrentLeaderAddress string
LeaderElected bool
}
type Raft struct {
r *raft.Raft
cfg conf.ClusterConfiguration
leaderObs *raft.Observer
leaderObsCh chan raft.Observation
changeLeaderCh chan ChangeLeaderNotification
closer chan struct{}
}
func (r *Raft) BootstrapCluster() error {
peers := makeConfiguration(r.cfg.Peers)
if f := r.r.BootstrapCluster(peers); f.Error() != nil {
return errors.WithMessage(f.Error(), "bootstrap cluster")
}
return nil
}
func (r *Raft) SyncApply(command []byte) (interface{}, error) {
f := r.r.Apply(command, defaultSyncTimeout)
if err := f.Error(); err != nil {
return nil, err
}
return f.Response(), nil
}
func (r *Raft) LeaderCh() <-chan ChangeLeaderNotification {
return r.changeLeaderCh
}
func (r *Raft) GracefulShutdown() error {
r.r.DeregisterObserver(r.leaderObs)
close(r.closer)
close(r.changeLeaderCh)
return r.r.Shutdown().Error()
}
func (r *Raft) listenLeader() {
for {
select {
case _, ok := <-r.leaderObsCh:
if !ok {
return
}
currentLeader := r.r.Leader()
select {
case r.changeLeaderCh <- ChangeLeaderNotification{
IsLeader: r.r.State() == raft.Leader,
CurrentLeaderAddress: string(currentLeader),
LeaderElected: currentLeader != "",
}:
default:
continue
}
case <-r.closer:
return
}
}
}
func NewRaft(tcpListener net.Listener, configuration conf.ClusterConfiguration, state raft.FSM) (*Raft, error) {
logStore, store, snapshotStore, err := makeStores(configuration)
if err != nil {
return nil, err
}
netLogger := &LoggerAdapter{name: "RAFT-NET"}
streamLayer := &StreamLayer{Listener: tcpListener}
timeout := time.Duration(configuration.ConnectTimeoutSeconds) * time.Second
config := &raft.NetworkTransportConfig{
Stream: streamLayer,
MaxPool: len(configuration.Peers),
Timeout: timeout,
Logger: netLogger,
ServerAddressProvider: transparentAddressProvider{},
}
trans := raft.NewNetworkTransportWithConfig(config)
cfg := raft.DefaultConfig()
cfg.Logger = &LoggerAdapter{name: "RAFT"}
cfg.NoSnapshotRestoreOnStart = true
cfg.LocalID = raft.ServerID(configuration.OuterAddress)
r, err := raft.NewRaft(cfg, state, logStore, store, snapshotStore, trans)
if err != nil {
return nil, errors.WithMessage(err, "create raft")
}
leaderObs, leaderObsCh := makeLeaderObserver()
r.RegisterObserver(leaderObs)
raft := &Raft{
r: r,
cfg: configuration,
leaderObs: leaderObs,
leaderObsCh: leaderObsCh,
changeLeaderCh: make(chan ChangeLeaderNotification, 10),
closer: make(chan struct{}),
}
go raft.listenLeader()
return raft, nil
}
func makeLeaderObserver() (*raft.Observer, chan raft.Observation) {
ch := make(chan raft.Observation)
obs := raft.NewObserver(ch, false, func(o *raft.Observation) bool {
_, ok := o.Data.(raft.LeaderObservation)
return ok
})
return obs, ch
}
func makeConfiguration(peers []string) raft.Configuration {
servers := make([]raft.Server, len(peers))
for i, peer := range peers {
servers[i] = raft.Server{
ID: raft.ServerID(peer),
Address: raft.ServerAddress(peer),
}
}
return raft.Configuration{
Servers: servers,
}
}
func makeStores(configuration conf.ClusterConfiguration) (raft.LogStore, raft.StableStore, raft.SnapshotStore, error) {
if configuration.InMemory {
dbStore := raft.NewInmemStore()
snapStore := raft.NewInmemSnapshotStore()
return dbStore, dbStore, snapStore, nil
} else {
dbStore, err := raftboltdb.NewBoltStore(filepath.Join(configuration.DataDir, dbFile))
if err != nil {
return nil, nil, nil, errors.WithMessage(err, "create db")
}
snapStore, err := raft.NewFileSnapshotStore(configuration.DataDir, 1, os.Stdout)
if err != nil {
return nil, nil, nil, errors.WithMessage(err, "create snapshot store")
}
return dbStore, dbStore, snapStore, nil
}
}
-22
View File
@@ -1,22 +0,0 @@
package raft
import (
"github.com/hashicorp/raft"
"net"
"time"
)
type StreamLayer struct {
net.Listener
}
func (r *StreamLayer) Dial(address raft.ServerAddress, timeout time.Duration) (net.Conn, error) {
return net.DialTimeout("tcp", string(address), timeout)
}
type transparentAddressProvider struct {
}
func (t transparentAddressProvider) ServerAddr(id raft.ServerID) (raft.ServerAddress, error) {
return raft.ServerAddress(id), nil
}
+145
View File
@@ -0,0 +1,145 @@
package service
import (
"github.com/googollee/go-socket.io"
"sync"
"time"
)
type SocketConn struct {
socketio.Socket
EstablishedAt time.Time
}
type roomStats struct {
m map[string]map[string]*SocketConn
sync.RWMutex
}
func NewRoomStats() *roomStats {
return &roomStats{
m: make(map[string]map[string]*SocketConn),
}
}
func (rs *roomStats) Join(room string, socket socketio.Socket) error {
rs.Lock()
sockets, ok := rs.m[room]
if !ok {
sockets = make(map[string]*SocketConn)
}
sockets[socket.Id()] = &SocketConn{socket, time.Now()}
rs.m[room] = sockets
rs.Unlock()
return nil
}
func (rs *roomStats) GetConnection(instanceId, sockId string) (*SocketConn, bool) {
rs.RLock()
defer rs.RUnlock()
if m, ok := rs.m[":"+instanceId]; !ok {
return nil, false
} else if s, ok := m[sockId]; !ok {
return nil, false
} else {
return s, true
}
}
func (rs *roomStats) Leave(room string, socket socketio.Socket) error {
rs.Lock()
defer rs.Unlock()
sockets, ok := rs.m[room]
if !ok {
return nil
}
delete(sockets, socket.Id())
if len(sockets) == 0 {
delete(rs.m, room)
return nil
}
rs.m[room] = sockets
return nil
}
func (rs *roomStats) RoomCount(room string) map[string]*SocketConn {
rs.RLock()
defer rs.RUnlock()
return rs.m[room]
}
func (rs *roomStats) RoomsCount() map[string]map[string]int {
rs.RLock()
defer rs.RUnlock()
result := map[string]map[string]int{}
for room, value := range rs.m {
instanceId := room[1:37]
module := room[37:]
if module == "" {
continue
}
if _, ok := result[instanceId]; !ok {
result[instanceId] = map[string]int{module: len(value)}
} else {
result[instanceId][module] = len(value)
}
}
return result
}
func (rs *roomStats) GetModuleConnectionMap() map[string]map[string][]string {
rs.RLock()
defer rs.RUnlock()
result := make(map[string]map[string][]string)
for room, value := range rs.m {
instanceId := room[1:37]
module := room[37:]
if module == "" {
continue
}
if _, ok := result[instanceId]; !ok {
result[instanceId] = make(map[string][]string)
}
for sockId := range value {
if arr, ok := result[instanceId][module]; !ok {
result[instanceId][module] = []string{sockId}
} else {
result[instanceId][module] = append(arr, sockId)
}
}
}
return result
}
func (rs *roomStats) Send(ignore socketio.Socket, room, event string, args ...interface{}) error {
rs.RLock()
sockets := rs.m[room]
for id, s := range sockets {
if ignore != nil && ignore.Id() == id {
continue
}
s.Emit(event, args...)
}
rs.RUnlock()
return nil
}
func (rs *roomStats) Len(room string) int {
return len(rs.m[room])
}
func (rs *roomStats) RemoveSocketConn(sockId string) {
rs.Lock()
for room, store := range rs.m {
delete(store, sockId)
if len(store) == 0 {
delete(rs.m, room)
}
}
rs.Unlock()
}
-28
View File
@@ -1,28 +0,0 @@
package service
import (
"github.com/integration-system/isp-lib/structure"
"isp-config-service/store/state"
)
var (
ClusterMeshService clusterMeshService
)
type clusterMeshService struct{}
func (clusterMeshService) HandleUpdateBackendDeclarationCommand(declaration structure.BackendDeclaration, state state.WritableState) {
changed := state.WritableMesh().UpsertBackend(declaration)
if changed {
DiscoveryService.BroadcastModuleAddresses(declaration.ModuleName, state.Mesh())
RoutesService.BroadcastRoutes(state.Mesh())
}
}
func (clusterMeshService) HandleDeleteBackendDeclarationCommand(declaration structure.BackendDeclaration, state state.WritableState) {
deleted := state.WritableMesh().DeleteBackend(declaration)
if deleted {
DiscoveryService.BroadcastModuleAddresses(declaration.ModuleName, state.Mesh())
RoutesService.BroadcastRoutes(state.Mesh())
}
}
-90
View File
@@ -1,90 +0,0 @@
package service
import (
log "github.com/integration-system/isp-log"
codes2 "google.golang.org/grpc/codes"
"isp-config-service/cluster"
"isp-config-service/codes"
"isp-config-service/domain"
"isp-config-service/holder"
"isp-config-service/model"
"isp-config-service/store/state"
)
var (
CommonConfigService = commonConfigService{}
)
type commonConfigService struct{}
func (s commonConfigService) HandleDeleteConfigsCommand(deleteCommonConfig cluster.DeleteCommonConfig, state state.WritableState) cluster.ResponseWithError {
links := s.GetCommonConfigLinks(deleteCommonConfig.Id, state)
if len(links) > 0 {
return cluster.NewResponse(domain.DeleteCommonConfigResponse{Deleted: false, Links: links})
}
ids := []string{deleteCommonConfig.Id}
deleted := state.WritableCommonConfigs().DeleteByIds(ids)
if holder.ClusterClient.IsLeader() {
// TODO handle db errors
_, err := model.CommonConfigRep.Delete(ids)
if err != nil {
log.WithMetadata(map[string]interface{}{
"configIds": ids,
}).Errorf(codes.DatabaseOperationError, "delete configs: %v", err)
}
}
return cluster.NewResponse(domain.DeleteCommonConfigResponse{Deleted: deleted > 0})
}
func (s commonConfigService) HandleUpsertConfigCommand(upsertConfig cluster.UpsertCommonConfig, state state.WritableState) cluster.ResponseWithError {
config := upsertConfig.Config
configsByName := state.CommonConfigs().GetByName(config.Name)
if upsertConfig.Create {
if len(configsByName) > 0 {
return cluster.NewResponseErrorf(codes2.AlreadyExists, "common config with name %s already exists", upsertConfig.Config.Name)
}
config = state.WritableCommonConfigs().Create(config)
} else {
// Update
configs := state.CommonConfigs().GetByIds([]string{config.Id})
if len(configs) == 0 {
return cluster.NewResponseErrorf(codes2.NotFound, "common config with id %s not found", config.Id)
}
if len(configsByName) > 0 && configs[0].Id != configsByName[0].Id {
return cluster.NewResponseErrorf(codes2.AlreadyExists, "common config with name %s already exists", upsertConfig.Config.Name)
}
config.CreatedAt = configs[0].CreatedAt
state.WritableCommonConfigs().UpdateById(config)
}
if holder.ClusterClient.IsLeader() {
// TODO handle db errors
_, err := model.CommonConfigRep.Upsert(config)
if err != nil {
log.WithMetadata(map[string]interface{}{
"config": config,
}).Errorf(codes.DatabaseOperationError, "upsert common config: %v", err)
}
}
if !upsertConfig.Create {
configsToBroadcast := state.Configs().FilterByCommonConfigs([]string{config.Id})
ConfigService.BroadcastNewConfig(state, configsToBroadcast...)
}
return cluster.NewResponse(config)
}
func (s commonConfigService) GetCommonConfigLinks(commonConfigId string, state state.ReadonlyState) domain.CommonConfigLinks {
configs := state.Configs().FilterByCommonConfigs([]string{commonConfigId})
result := make(domain.CommonConfigLinks)
for _, c := range configs {
module := state.Modules().GetById(c.ModuleId)
if module != nil {
if configs, ok := result[module.Name]; ok {
result[module.Name] = append(configs, c.Name)
} else {
result[module.Name] = []string{c.Name}
}
}
}
return result
}
-215
View File
@@ -1,215 +0,0 @@
package service
import (
"encoding/json"
"fmt"
"github.com/integration-system/bellows"
"github.com/integration-system/isp-lib/utils"
log "github.com/integration-system/isp-log"
"github.com/pkg/errors"
"github.com/xeipuuv/gojsonschema"
codes2 "google.golang.org/grpc/codes"
"isp-config-service/cluster"
"isp-config-service/codes"
"isp-config-service/domain"
"isp-config-service/entity"
"isp-config-service/holder"
"isp-config-service/model"
"isp-config-service/store/state"
)
var (
ConfigService = configService{}
)
const ConfigWatchersRoomSuffix = "_config"
type configService struct{}
type validationSchemaError struct {
Description map[string]string
}
func (e validationSchemaError) Error() string {
resp := ""
for field, desc := range e.Description {
resp = fmt.Sprintf("%s- %s%s\n", resp, field, desc)
}
return resp
}
func (cs configService) GetCompiledConfig(moduleName string, state state.ReadonlyState) (map[string]interface{}, error) {
module := state.Modules().GetByName(moduleName)
if module == nil {
return nil, errors.Errorf("module with name %s not found", moduleName)
}
config := state.Configs().GetActiveByModuleId(module.Id)
if config == nil {
return nil, errors.Errorf("no active configs for moduleName %s, moduleId %s", moduleName, module.Id)
}
return cs.CompileConfig(config.Data, state, config.CommonConfigs...), nil
}
func (configService) CompileConfig(data map[string]interface{}, state state.ReadonlyState, commonConfigsIds ...string) map[string]interface{} {
commonConfigs := state.CommonConfigs().GetByIds(commonConfigsIds)
configsToMerge := make([]map[string]interface{}, 0, len(commonConfigs))
for _, common := range commonConfigs {
configsToMerge = append(configsToMerge, common.Data)
}
configsToMerge = append(configsToMerge, data)
return mergeNestedMaps(configsToMerge...)
}
func (configService) HandleActivateConfigCommand(activateConfig cluster.ActivateConfig, state state.WritableState) cluster.ResponseWithError {
configs := state.Configs().GetByIds([]string{activateConfig.ConfigId})
if len(configs) == 0 {
return cluster.NewResponseErrorf(codes2.NotFound, "config with id %s not found", activateConfig.ConfigId)
}
config := configs[0]
affected := state.WritableConfigs().Activate(config, activateConfig.Date)
if holder.ClusterClient.IsLeader() {
for _, c := range affected {
// TODO handle db errors
_, err := model.ConfigRep.Upsert(c)
if err != nil {
log.WithMetadata(map[string]interface{}{
"config": config,
}).Errorf(codes.DatabaseOperationError, "upsert config: %v", err)
}
}
}
return cluster.NewResponse(affected[len(affected)-1])
}
func (configService) HandleDeleteConfigsCommand(deleteConfigs cluster.DeleteConfigs, state state.WritableState) int {
ids := deleteConfigs.Ids
deleted := state.WritableConfigs().DeleteByIds(ids)
if holder.ClusterClient.IsLeader() {
// TODO handle db errors
_, err := model.ConfigRep.Delete(ids)
if err != nil {
log.WithMetadata(map[string]interface{}{
"configIds": ids,
}).Errorf(codes.DatabaseOperationError, "delete configs: %v", err)
}
}
return deleted
}
func (cs configService) HandleUpsertConfigCommand(upsertConfig cluster.UpsertConfig, state state.WritableState) cluster.ResponseWithError {
config := upsertConfig.Config
module := state.Modules().GetById(config.ModuleId)
if module == nil {
return cluster.NewResponseErrorf(codes2.NotFound, "moduleId %s not found", config.ModuleId)
}
schemaStorage := state.Schemas().GetByModuleIds([]string{config.ModuleId})
if len(schemaStorage) == 0 {
return cluster.NewResponseErrorf(codes2.NotFound, "schema for moduleId %s not found", config.ModuleId)
}
dataForValidate := cs.CompileConfig(config.Data, state, config.CommonConfigs...)
validSchema, err := cs.validateSchema(schemaStorage[0], dataForValidate)
if !upsertConfig.Unsafe && err != nil {
switch err := err.(type) {
case validationSchemaError:
return cluster.NewResponse(
domain.CreateUpdateConfigResponse{
Config: nil,
ErrorDetails: err.Description,
})
default:
return cluster.NewResponseErrorf(codes2.Internal, "%v", err)
}
}
if upsertConfig.Create {
config = state.WritableConfigs().Create(config)
} else {
// Update
configs := state.Configs().GetByIds([]string{config.Id})
if len(configs) == 0 {
return cluster.NewResponseErrorf(codes2.NotFound, "config with id %s not found", config.Id)
}
config.CreatedAt = configs[0].CreatedAt
state.WritableConfigs().UpdateById(config)
}
if holder.ClusterClient.IsLeader() {
// TODO handle db errors
_, err := model.ConfigRep.Upsert(config)
if err != nil {
log.WithMetadata(map[string]interface{}{
"config": config,
}).Errorf(codes.DatabaseOperationError, "upsert config: %v", err)
}
}
cs.BroadcastNewConfig(state, config)
return cluster.NewResponse(domain.CreateUpdateConfigResponse{
Config: &domain.ConfigModuleInfo{
Config: config,
Valid: validSchema,
},
ErrorDetails: nil,
})
}
func (cs configService) BroadcastNewConfig(state state.ReadonlyState, configs ...entity.Config) {
for _, cfg := range configs {
moduleId := cfg.ModuleId
module := state.Modules().GetById(moduleId)
moduleName := module.Name
room := moduleName + ConfigWatchersRoomSuffix
compiledConfig, err := cs.GetCompiledConfig(moduleName, state)
if err != nil {
go cs.broadcast(room, utils.ConfigError, []byte(err.Error()))
continue
}
data, err := json.Marshal(compiledConfig)
if err != nil {
go cs.broadcast(room, utils.ConfigError, []byte(err.Error()))
continue
}
go cs.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)
}
}
func (configService) validateSchema(schema entity.ConfigSchema, data map[string]interface{}) (bool, error) {
schemaLoader := gojsonschema.NewGoLoader(schema.Schema)
documentLoader := gojsonschema.NewGoLoader(data)
if result, err := gojsonschema.Validate(schemaLoader, documentLoader); err != nil {
return false, err
} else if result.Valid() {
return true, nil
} else {
desc := make(map[string]string)
for _, value := range result.Errors() {
desc[value.Field()] = value.Description()
}
return false, validationSchemaError{Description: desc}
}
}
func mergeNestedMaps(maps ...map[string]interface{}) map[string]interface{} {
if len(maps) == 1 {
return maps[0]
}
result := bellows.Flatten(maps[0])
for i := 1; i < len(maps); i++ {
newFlatten := bellows.Flatten(maps[i])
for k, v := range newFlatten {
result[k] = v
}
}
return bellows.Expand(result).(map[string]interface{})
}
-37
View File
@@ -1,37 +0,0 @@
package service
import (
"encoding/json"
"github.com/stretchr/testify/assert"
"isp-config-service/entity"
"testing"
)
func TestConfigService_validateSchema(t *testing.T) {
var (
a = assert.New(t)
schemaDesc = []byte(`{"schema":{"properties":{"configuration":{"required":["address","token"],"properties":{"address":{"type":"string","title":"Адрес"},"token":{"type":"string","title":"Токен"}},"additionalProperties":false,"type":"object"}},"additionalProperties":false,"type":"object","title":"Remote config"},"title":"module_name"}`)
validData = map[string]interface{}{"configuration": map[string]interface{}{"address": "127.0.0.1", "token": "token"}}
invalidValue = map[string]interface{}{"configuration": map[string]interface{}{"address": 127001, "token": "token"}}
invalidName = map[string]interface{}{"config": map[string]interface{}{"test": "127.0.0.1", "token": "token"}}
schema entity.ConfigSchema
valid bool
err error
)
a.NoError(json.Unmarshal(schemaDesc, &schema))
valid, err = ConfigService.validateSchema(schema, validData)
a.NoError(err)
a.True(valid)
valid, err = ConfigService.validateSchema(schema, invalidValue)
a.Error(err)
a.False(valid)
valid, err = ConfigService.validateSchema(schema, invalidName)
a.Error(err)
a.False(valid)
}
-109
View File
@@ -1,109 +0,0 @@
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"
"sync"
"time"
)
var (
DiscoveryService = NewDiscoveryService()
)
type discoveryService struct {
subs map[string][]string
lock sync.RWMutex
}
func (ds *discoveryService) HandleDisconnect(connId string) {
ds.lock.Lock()
defer ds.lock.Unlock()
if events, ok := ds.subs[connId]; ok {
holder.EtpServer.Rooms().LeaveByConnId(connId, events...)
delete(ds.subs, connId)
}
}
func (ds *discoveryService) Subscribe(conn etp.Conn, modules []string, mesh state.ReadonlyMesh) {
if len(modules) == 0 {
return
}
ds.lock.Lock()
defer ds.lock.Unlock()
eventsAddresses := make([][]structure.AddressConfiguration, 0, len(modules))
events := make([]string, 0, len(modules))
for _, module := range modules {
event := utils.ModuleConnected(module)
addressList := mesh.GetModuleAddresses(module)
eventsAddresses = append(eventsAddresses, addressList)
events = append(events, event)
}
ds.subs[conn.ID()] = events
holder.EtpServer.Rooms().Join(conn, events...)
go func(events []string, eventsAddresses [][]structure.AddressConfiguration, conn etp.Conn) {
for i := range events {
event := events[i]
addressList := eventsAddresses[i]
err := ds.sendAddrList(conn, event, addressList)
if err != nil {
log.Errorf(codes.DiscoveryServiceSendModulesError, "send module connected %v", err)
}
}
}(events, eventsAddresses, conn)
}
func (ds *discoveryService) BroadcastModuleAddresses(moduleName string, mesh state.ReadonlyMesh) {
ds.lock.RLock()
defer ds.lock.RUnlock()
event := utils.ModuleConnected(moduleName)
addressList := mesh.GetModuleAddresses(moduleName)
go func(room, event string, addressList []structure.AddressConfiguration) {
err := ds.broadcastAddrList(room, event, addressList)
if err != nil {
log.Errorf(codes.DiscoveryServiceSendModulesError, "broadcast module connected %v", err)
}
}(event, event, addressList)
}
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.EtpServer.BroadcastToRoom(room, event, bytes)
if err != nil {
return err
}
}
return nil
}
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(context.Background(), event, bytes)
}, bf)
if err != nil {
return err
}
}
return nil
}
func NewDiscoveryService() *discoveryService {
return &discoveryService{
subs: make(map[string][]string),
}
}
-179
View File
@@ -1,179 +0,0 @@
package service
import (
"github.com/integration-system/isp-lib/structure"
log "github.com/integration-system/isp-log"
"isp-config-service/cluster"
"isp-config-service/codes"
"isp-config-service/domain"
"isp-config-service/entity"
"isp-config-service/holder"
"isp-config-service/model"
"isp-config-service/store/state"
"sort"
)
var (
ModuleRegistryService = moduleRegistryService{}
)
type moduleRegistryService struct{}
func (s moduleRegistryService) HandleModuleConnectedCommand(module entity.Module, state state.WritableState) {
existedModule := state.WritableModules().GetByName(module.Name)
if existedModule == nil {
state.WritableModules().Create(module)
} else {
module.Id = existedModule.Id
module.CreatedAt = existedModule.CreatedAt
module.LastDisconnectedAt = existedModule.LastDisconnectedAt
state.WritableModules().UpdateByName(module)
}
if holder.ClusterClient.IsLeader() {
// TODO handle db errors
_, err := model.ModuleRep.Upsert(module)
if err != nil {
log.WithMetadata(map[string]interface{}{
"module": module,
}).Errorf(codes.DatabaseOperationError, "upsert module: %v", err)
}
}
}
func (moduleRegistryService) HandleModuleDisconnectedCommand(module entity.Module, state state.WritableState) {
existedModule := state.WritableModules().GetByName(module.Name)
if existedModule == nil {
state.WritableModules().Create(module)
} else {
module.Id = existedModule.Id
module.CreatedAt = existedModule.CreatedAt
module.LastConnectedAt = existedModule.LastConnectedAt
state.WritableModules().UpdateByName(module)
}
if holder.ClusterClient.IsLeader() {
// TODO handle db errors
_, err := model.ModuleRep.Upsert(module)
if err != nil {
log.WithMetadata(map[string]interface{}{
"module": module,
}).Errorf(codes.DatabaseOperationError, "upsert module: %v", err)
}
}
}
func (moduleRegistryService) HandleDeleteModulesCommand(deleteModules cluster.DeleteModules, state state.WritableState) int {
ids := deleteModules.Ids
deletedModules := state.WritableModules().DeleteByIds(ids)
configsToDelete := state.WritableConfigs().GetByModuleIds(ids)
confIds := make([]string, 0, len(configsToDelete))
for _, conf := range configsToDelete {
confIds = append(confIds, conf.Id)
}
state.WritableConfigs().DeleteByIds(confIds)
schemasToDelete := state.WritableSchemas().GetByModuleIds(ids)
schemaIds := make([]string, 0, len(schemasToDelete))
for _, schema := range schemasToDelete {
schemaIds = append(schemaIds, schema.Id)
}
state.WritableSchemas().DeleteByIds(schemaIds)
if holder.ClusterClient.IsLeader() {
// TODO handle db errors
_, err := model.ModuleRep.Delete(ids)
if err != nil {
log.WithMetadata(map[string]interface{}{
"moduleIds": ids,
}).Errorf(codes.DatabaseOperationError, "delete modules: %v", err)
}
_, err = model.ConfigRep.Delete(confIds)
if err != nil {
log.WithMetadata(map[string]interface{}{
"configIds": confIds,
}).Errorf(codes.DatabaseOperationError, "delete configs: %v", err)
}
_, err = model.SchemaRep.Delete(schemaIds)
if err != nil {
log.WithMetadata(map[string]interface{}{
"schemaIds": schemaIds,
}).Errorf(codes.DatabaseOperationError, "delete schemas: %v", err)
}
}
return len(deletedModules)
}
func (moduleRegistryService) GetAggregatedModuleInfo(state state.ReadonlyState) []domain.ModuleInfo {
modules := state.Modules().GetAll()
modulesLen := len(modules)
result := make([]domain.ModuleInfo, 0, modulesLen)
resMap := make(map[string]domain.ModuleInfo, modulesLen)
idList := make([]string, modulesLen)
for i, module := range modules {
idList[i] = module.Id
active := state.Mesh().BackendExist(structure.BackendDeclaration{ModuleName: module.Name})
info := domain.ModuleInfo{
Id: module.Id,
Name: module.Name,
Active: active,
CreatedAt: module.CreatedAt,
LastConnectedAt: module.LastConnectedAt,
LastDisconnectedAt: module.LastDisconnectedAt,
}
resMap[module.Id] = info
}
configs := state.Configs().GetByModuleIds(idList)
for _, cfg := range configs {
info := resMap[cfg.ModuleId]
info.Configs = append(info.Configs, domain.ConfigModuleInfo{
Config: cfg,
Valid: false,
})
resMap[cfg.ModuleId] = info
}
schemas := state.Schemas().GetByModuleIds(idList)
for _, s := range schemas {
info := resMap[s.ModuleId]
schema := s.Schema
info.ConfigSchema = &schema
for i, config := range info.Configs {
dataForValidate := ConfigService.CompileConfig(config.Data, state, config.CommonConfigs...)
info.Configs[i].Valid, _ = ConfigService.validateSchema(s, dataForValidate)
}
resMap[s.ModuleId] = info
}
for key := range resMap {
info := resMap[key]
backends := state.Mesh().GetBackends(info.Name)
conns := make([]domain.Connection, 0, len(backends))
for _, back := range backends {
con := domain.Connection{
Version: back.Version,
LibVersion: back.LibVersion,
Address: back.Address,
Endpoints: back.Endpoints,
}
sort.Slice(con.Endpoints, func(i, j int) bool {
return con.Endpoints[i].Path < con.Endpoints[j].Path
})
con.EstablishedAt = info.LastConnectedAt
conns = append(conns, con)
}
sort.Slice(conns, func(i, j int) bool {
return conns[i].EstablishedAt.Before(conns[j].EstablishedAt)
})
info.Status = conns
result = append(result, info)
}
sort.Slice(result, func(i, j int) bool {
return result[i].Name < result[j].Name
})
return result
}
+63
View File
@@ -0,0 +1,63 @@
package service
import (
"sync"
libSt "github.com/integration-system/isp-lib/structure"
)
type RouterTables struct {
Routes map[string]libSt.BackendDeclaration
sync.RWMutex
}
func (routerTables *RouterTables) DeleteRoute(socketId string) bool {
routerTables.Lock()
defer routerTables.Unlock()
changed := false
for k := range (*routerTables).Routes {
if k == socketId {
delete((*routerTables).Routes, k)
changed = true
}
}
return changed
}
func (routerTables *RouterTables) GetRoutes() *libSt.RoutingConfig {
routerTables.RLock()
defer routerTables.RUnlock()
var routes = libSt.RoutingConfig{}
for _, v := range (*routerTables).Routes {
routes = append(routes, v)
}
return &routes
}
func (routerTables *RouterTables) AddAddressOrUpdate(socketId string, backendConfig libSt.BackendDeclaration) bool {
routerTables.Lock()
defer routerTables.Unlock()
exists := false
changed := false
for k, v := range (*routerTables).Routes {
if k == socketId {
if !v.IsPathsEqual(backendConfig.Endpoints) {
(*routerTables).Routes[socketId] = backendConfig
changed = true
}
exists = true
}
}
if !exists {
if (*routerTables).Routes != nil {
(*routerTables).Routes[socketId] = backendConfig
} else {
(*routerTables).Routes = map[string]libSt.BackendDeclaration{socketId: backendConfig}
}
changed = true
}
return changed
}
-75
View File
@@ -1,75 +0,0 @@
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"
"time"
)
const (
RoutesSubscribersRoom = "__routesSubscribers"
)
var RoutesService routesService
type routesService struct{}
func (rs *routesService) HandleDisconnect(connId string) {
holder.EtpServer.Rooms().LeaveByConnId(connId, RoutesSubscribersRoom)
}
func (rs *routesService) SubscribeRoutes(conn etp.Conn, mesh state.ReadonlyMesh) {
holder.EtpServer.Rooms().Join(conn, RoutesSubscribersRoom)
routes := mesh.GetRoutes()
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)
}
}(conn, routes)
}
func (rs *routesService) BroadcastRoutes(mesh state.ReadonlyMesh) {
routes := mesh.GetRoutes()
go func(routes structure.RoutingConfig) {
err := rs.broadcastRoutes(utils.ConfigSendRoutesChanged, routes)
if err != nil {
log.Errorf(codes.RoutesServiceSendRoutesError, "broadcast routes %v", err)
}
}(routes)
}
func (rs *routesService) broadcastRoutes(event string, routes structure.RoutingConfig) error {
if bytes, err := json.Marshal(routes); err != nil {
return err
} else {
err = holder.EtpServer.BroadcastToRoom(RoutesSubscribersRoom, event, bytes)
if err != nil {
return err
}
}
return nil
}
func (rs *routesService) sendRoutes(conn etp.Conn, event string, routes structure.RoutingConfig) error {
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(context.Background(), event, bytes)
}, bf)
if err != nil {
return err
}
}
return nil
}
-36
View File
@@ -1,36 +0,0 @@
package service
import (
log "github.com/integration-system/isp-log"
"github.com/pkg/errors"
"isp-config-service/codes"
"isp-config-service/entity"
"isp-config-service/holder"
"isp-config-service/model"
"isp-config-service/store/state"
)
var (
SchemaService schemaService
)
type schemaService struct{}
func (schemaService) HandleUpdateConfigSchemaCommand(schema entity.ConfigSchema, state state.WritableState) error {
module := state.Modules().GetById(schema.ModuleId)
if module == nil {
return errors.Errorf("module with id %s not found", schema.ModuleId)
}
schema = state.WritableSchemas().Upsert(schema)
if holder.ClusterClient.IsLeader() {
// TODO handle db errors
_, err := model.SchemaRep.Upsert(schema)
if err != nil {
log.WithMetadata(map[string]interface{}{
"schema": schema,
}).Errorf(codes.DatabaseOperationError, "upsert schema: %v", err)
}
}
return nil
}
+72
View File
@@ -0,0 +1,72 @@
package service
import (
"github.com/googollee/go-engine.io"
"sync"
)
type StoreOption func(ss *sessionsStore)
type sessionsStore struct {
sessions map[string]engineio.Conn
locker sync.RWMutex
onRemove func(id string)
onSet func(id string, conn engineio.Conn)
}
func (s *sessionsStore) Get(id string) engineio.Conn {
s.locker.RLock()
defer s.locker.RUnlock()
ret, ok := s.sessions[id]
if !ok {
return nil
}
return ret
}
func (s *sessionsStore) Set(id string, conn engineio.Conn) {
s.locker.Lock()
defer s.locker.Unlock()
s.sessions[id] = conn
if s.onSet != nil {
s.onSet(id, conn)
}
}
func (s *sessionsStore) Remove(id string) {
s.locker.Lock()
defer s.locker.Unlock()
delete(s.sessions, id)
if s.onRemove != nil {
s.onRemove(id)
}
}
func NewSessionStore(opts ...StoreOption) engineio.Sessions {
ss := &sessionsStore{sessions: make(map[string]engineio.Conn)}
for _, o := range opts {
o(ss)
}
return ss
}
func WithOnRemoveCallback(f func(id string)) StoreOption {
return func(ss *sessionsStore) {
ss.onRemove = f
}
}
func WithOnSetCallback(f func(id string, conn engineio.Conn)) StoreOption {
return func(ss *sessionsStore) {
ss.onSet = f
}
}
+71
View File
@@ -0,0 +1,71 @@
package service
import (
"errors"
"fmt"
"time"
"isp-config-service/entity"
"isp-config-service/model"
"github.com/integration-system/isp-lib/logger"
"github.com/integration-system/isp-lib/utils"
)
func Disonnect(instanceUuid string, moduleName string) error {
err := model.ModulesRep.UpdateModuleDisconnect(instanceUuid, moduleName)
if err != nil {
logger.Warn(err)
return errors.New(utils.ServiceError)
}
return nil
}
func NewConnection(instanceUuid string, moduleName string) error {
instance, err := model.InstanceRep.GetInstanceByUuid(instanceUuid)
if err != nil {
logger.Error(err)
return errors.New(utils.ServiceError)
}
if instance.Id == 0 {
return errors.New(fmt.Sprintf("The instance with uuid: %s not found", instanceUuid))
}
module, err := model.ModulesRep.GetModuleByInstanceIdAndName(instance.Id, moduleName)
if err != nil {
logger.Error(err)
return errors.New(utils.ServiceError)
}
if module.Id == 0 {
module.Name = moduleName
module.InstanceId = instance.Id
module.LastConnectedAt = time.Now()
module, err = model.ModulesRep.CreateModule(module)
if err != nil {
logger.Error(err)
return errors.New(utils.ServiceError)
}
return nil
} else {
module.LastConnectedAt = time.Now()
module, err = model.ModulesRep.UpdateModule(module)
if err != nil {
logger.Error(err)
return errors.New(utils.ServiceError)
}
return nil
}
}
func GetConfig(instanceUuid string, moduleName string) (*entity.Config, error) {
config, err := model.ConfigRep.GetConfigByInstanceUUIDAndModuleName(instanceUuid, moduleName)
if err != nil {
logger.Error(err)
return nil, errors.New(utils.ServiceError)
}
if config == nil {
errorMessage := "Active config for " + instanceUuid + ":" + moduleName + " not found"
logger.Warn(errorMessage)
return nil, errors.New(errorMessage)
}
return config, nil
}
+99
View File
@@ -0,0 +1,99 @@
package socket
import (
"github.com/googollee/go-socket.io"
"github.com/integration-system/isp-lib/utils"
"sync"
"time"
)
const (
defaultTimeout = 1 * time.Second
)
type Record struct {
data interface{}
future *time.Timer
}
type broadcaster struct {
Server *socketio.Server
AwaitNewRecordTimeout time.Duration
configMap map[string]*Record
routesMap map[string]*Record
converterMap map[string]*Record
routerMap map[string]*Record
configLock sync.Mutex
routesLock sync.Mutex
converterLock sync.Mutex
routerLock sync.Mutex
}
func (b *broadcaster) BroadcastConfig(moduleKey string, data interface{}, callback func(data interface{})) {
b.doBroadcast(moduleKey, data, utils.ConfigSendConfigChanged, &b.configLock, b.configMap, callback)
}
func (b *broadcaster) BroadcastRoutes(instanceId string, data interface{}, callback func(data interface{})) {
b.doBroadcast(instanceId, data, utils.ConfigSendRoutesChanged, &b.routesLock, b.routesMap, callback)
}
/*func (b *broadcaster) BroadcastConverterAddressList(instanceId string, data interface{}, callback func(data interface{})) {
b.doBroadcast(instanceId, data, utils.SendNewConverterConnected, &b.converterLock, b.converterMap, callback)
}
func (b *broadcaster) BroadcastRouterAddressList(instanceId string, data interface{}, callback func(data interface{})) {
b.doBroadcast(instanceId, data, utils.SendNewRouterConnected, &b.routerLock, b.routerMap, callback)
}*/
func (b *broadcaster) doBroadcast(
key string,
data interface{},
event string,
lock *sync.Mutex,
store map[string]*Record,
callback func(data interface{}),
) {
lock.Lock()
defer lock.Unlock()
if r, present := store[key]; present {
r.data = data
if r.future.Stop() {
r.future.Reset(b.AwaitNewRecordTimeout)
}
} else {
r := &Record{
data: data,
}
r.future = time.AfterFunc(b.AwaitNewRecordTimeout, func() {
lock.Lock()
if r.data != nil {
b.Server.BroadcastTo(key, event, r.data)
if callback != nil {
callback(r.data)
}
}
delete(store, key)
lock.Unlock()
})
store[key] = r
}
}
func NewBroadcaster(server *socketio.Server, awaitNewRecordTimeout time.Duration) *broadcaster {
timeout := awaitNewRecordTimeout
if timeout <= 0 {
timeout = defaultTimeout
}
return &broadcaster{
Server: server,
AwaitNewRecordTimeout: timeout,
configMap: map[string]*Record{},
routesMap: map[string]*Record{},
converterMap: map[string]*Record{},
routerMap: map[string]*Record{},
}
}
+154
View File
@@ -0,0 +1,154 @@
package socket
import (
"encoding/json"
"github.com/cenkalti/backoff"
"github.com/googollee/go-socket.io"
"github.com/integration-system/isp-lib/logger"
"github.com/integration-system/isp-lib/structure"
"github.com/integration-system/isp-lib/utils"
"sync"
"time"
)
var (
discoverersMap = make(map[string]*Discoverer)
discoverersLock sync.RWMutex
)
type channelIdList []string
type Discoverer struct {
subs map[string]channelIdList
instanceId string
lock sync.RWMutex
}
func (d *Discoverer) OnDisconnection(channelId string) {
d.lock.Lock()
defer d.lock.Unlock()
newSubs := make(map[string]channelIdList, len(d.subs))
for event, list := range d.subs {
newList := make(channelIdList, 0)
for _, id := range list {
if id != channelId {
newList = append(newList, id)
}
}
if len(newList) > 0 {
newSubs[event] = newList
}
}
d.subs = newSubs
}
func (d *Discoverer) Subscribe(events []string, socket socketio.Socket) {
if len(events) == 0 {
return
}
channelId := socket.Id()
d.lock.Lock()
defer d.lock.Unlock()
connectedModulesEvents := getConnectedModulesEventMap(d.instanceId)
for _, event := range events {
if list, ok := d.subs[event]; ok {
d.subs[event] = append(list, channelId)
} else {
d.subs[event] = []string{channelId}
}
if addrList, ok := connectedModulesEvents[event]; ok {
d.sendAddrList(socket, event, addrList)
}
}
}
func (d *Discoverer) BroadcastModuleAddresses(moduleName string) {
d.lock.RLock()
defer d.lock.RUnlock()
event := utils.ModuleConnected(moduleName)
connectedModulesEvents := getConnectedModulesEventMap(d.instanceId)
addrList := connectedModulesEvents[event]
channelList, channelListPresent := d.subs[event]
if channelListPresent {
for _, id := range channelList {
if s, ok := GetConnectionById(d.instanceId, id); ok {
d.sendAddrList(s, event, addrList)
}
}
}
}
func (d *Discoverer) sendAddrList(socket socketio.Socket, event string, addressList []structure.AddressConfiguration) {
if addressList == nil {
addressList = []structure.AddressConfiguration{}
}
if bytes, err := json.Marshal(addressList); err != nil {
logger.Warn(err)
} else {
bf := backoff.WithMaxRetries(backoff.NewConstantBackOff(100*time.Millisecond), 3)
err := backoff.Retry(func() error {
return socket.Emit(event, string(bytes))
}, bf)
if err != nil {
logger.Error(err)
}
}
}
func GetModuleAddressList(instanceId string, moduleName string) []structure.AddressConfiguration {
event := utils.ModuleConnected(moduleName)
connectedModulesEvents := getConnectedModulesEventMap(instanceId)
addrList := connectedModulesEvents[event]
if addrList == nil {
return make([]structure.AddressConfiguration, 0)
}
return addrList
}
func getConnectedModulesEventMap(instanceId string) map[string][]structure.AddressConfiguration {
connectedModulesEventMap := make(map[string][]structure.AddressConfiguration)
connMap := GetModuleConnectionIdMapByInstanceId(instanceId)
for moduleName, channelIdList := range connMap {
event := utils.ModuleConnected(moduleName)
addrList := make([]structure.AddressConfiguration, 0)
backendConfigs := GetRoutes().Routes
for _, id := range channelIdList {
if cfg, ok := backendConfigs[id]; ok {
addrList = append(addrList, cfg.Address)
}
}
connectedModulesEventMap[event] = addrList
}
return connectedModulesEventMap
}
func getOrRegisterDiscoverer(instanceId string) *Discoverer {
discoverersLock.RLock()
d, ok := discoverersMap[instanceId]
discoverersLock.RUnlock()
if ok {
return d
}
discoverersLock.Lock()
defer discoverersLock.Unlock()
if d, ok := discoverersMap[instanceId]; ok {
return d
}
d = &Discoverer{
subs: make(map[string]channelIdList),
instanceId: instanceId,
}
discoverersMap[instanceId] = d
return d
}
+262
View File
@@ -0,0 +1,262 @@
package socket
import (
"encoding/json"
"github.com/asaskevich/govalidator"
"github.com/integration-system/isp-lib/bootstrap"
"github.com/integration-system/isp-lib/structure"
"isp-config-service/service"
"github.com/googollee/go-socket.io"
"github.com/integration-system/isp-lib/config/schema"
"github.com/integration-system/isp-lib/logger"
"github.com/integration-system/isp-lib/utils"
"isp-config-service/entity"
"isp-config-service/model"
)
const (
routesSubscribers = ":routes_subs"
)
var (
okMsg = "ok"
errorMsg = "error"
)
func RoutesSubscribersRoom(instanceUuid string) string {
return instanceUuid + routesSubscribers
}
func onError(so socketio.Socket, err error) {
logger.Warnf("error: %s", err)
}
func onDisconnect(so socketio.Socket) {
logger.Debugf("onDisconnect: %s", so.Id())
instanceUuid, moduleName, err := utils.ParseParameters(so.Request().URL.RawQuery)
if err != nil {
logger.Warn(err)
return
}
must(so.Leave(instanceUuid + moduleName))
must(so.Leave(instanceUuid))
must(so.Leave(RoutesSubscribersRoom(instanceUuid)))
_ = service.Disonnect(instanceUuid, moduleName)
discoverer := getOrRegisterDiscoverer(instanceUuid)
discoverer.OnDisconnection(so.Id())
discoverer.BroadcastModuleAddresses(moduleName)
if backendRoutes.DeleteRoute(so.Id()) {
BroadcastRoutesSnapshot(instanceUuid)
}
}
func onConnect(so socketio.Socket) {
logger.Debugf("onConnect: %s", so.Id())
instanceUuid, moduleName, err := utils.ParseParameters(so.Request().URL.RawQuery)
if err != nil {
_ = so.Emit(utils.ConfigError, err.Error())
return
}
err = service.NewConnection(instanceUuid, moduleName)
if err != nil {
_ = so.Emit(utils.ConfigError, err.Error())
return
}
must(so.Join(instanceUuid + moduleName))
must(so.Join(instanceUuid))
config, err := service.GetConfig(instanceUuid, moduleName)
if err != nil {
_ = so.Emit(utils.ConfigError, err.Error())
} else {
_ = so.Emit(
utils.ConfigSendConfigWhenConnected, config.Data.ToJSON(), func(so socketio.Socket, data string) {
logger.Debug("Client ACK with data: ", data)
},
)
}
}
func onReceivedModuleRequirements(so socketio.Socket, msg string) {
logger.Debugf("onReceivedModuleRequirements: %s %s", so.Id(), msg)
instanceUuid, _, err := utils.ParseParameters(so.Request().URL.RawQuery)
if err != nil {
_ = so.Emit(utils.ErrorConnection, map[string]string{"error": err.Error()})
return
}
declaration := bootstrap.ModuleRequirements{}
err = json.Unmarshal([]byte(msg), &declaration)
if err != nil {
_ = so.Emit(utils.ErrorConnection, map[string]string{"error": err.Error()})
logger.Debugf("onReceivedModuleRequirements: %s, error parse json data: %s", so.Id(), err.Error())
return
}
if declaration.RequireRoutes {
must(so.Join(RoutesSubscribersRoom(instanceUuid)))
SendRoutesSnapshot(so)
}
discoverer := getOrRegisterDiscoverer(instanceUuid)
discoverer.Subscribe(declaration.RequiredModules, so)
}
func onReceiveModuleReady(so socketio.Socket, msg string) {
logger.Debugf("onReceiveModuleReady: %s", so.Id())
handleModuleDeclaration(so, msg)
}
func onReceiveRoutesUpdate(so socketio.Socket, msg string) {
logger.Debugf("onReceiveRoutesUpdate: %s", so.Id())
handleModuleDeclaration(so, msg)
}
func onReceiveRemoteConfigSchema(so socketio.Socket, msg string) string {
logger.Debugf("onReceiveRemoteConfigSchema: %s %s", so.Id(), msg)
instanceUuid, moduleName, err := utils.ParseParameters(so.Request().URL.RawQuery)
if err != nil {
logger.Warn(err)
return errorMsg
}
module, err := model.ModulesRep.GetModulesByInstanceUuidAndName(instanceUuid, moduleName)
if err != nil {
logger.Warn(err)
return errorMsg
}
if module == nil {
logger.Warnf("Module '%s' in instance '%s' not found", moduleName, instanceUuid)
return errorMsg
}
s := new(schema.ConfigSchema)
if err := json.Unmarshal([]byte(msg), s); err != nil {
logger.Warn(err)
return errorMsg
}
res, err := model.SchemaRep.GetSchemasByModulesId([]int32{module.Id})
if err != nil {
logger.Warn(err)
return errorMsg
}
if len(res) > 0 {
schema := &res[0]
schema.Schema = s.Schema
schema.Version = s.Version
if _, err := model.SchemaRep.UpdateConfigSchema(schema); err != nil {
logger.Warn(err)
return errorMsg
}
/*if s.Version > schema.Version {
schema.Version = s.Version
schema.Schema = s.Schema
if _, err := model.SchemaRep.UpdateConfigSchema(schema); err != nil {
logger.Warn(err)
}
}*/
} else {
cs := &entity.ConfigSchema{
Version: s.Version,
Schema: s.Schema,
ModuleId: module.Id,
}
if _, err := model.SchemaRep.InsertConfigSchema(cs); err != nil {
logger.Warn(err)
return errorMsg
}
}
if len(s.DefaultConfig) == 0 {
return okMsg
}
configs, err := model.ConfigRep.GetConfigByInstanceUUIDAndModuleName(instanceUuid, moduleName)
if err != nil {
logger.Warn(err)
return errorMsg
}
if configs != nil {
return okMsg
}
config := entity.Config{
ModuleId: module.Id,
Name: module.Name,
Data: s.DefaultConfig,
Active: true,
Version: 1,
}
_, err = model.ConfigRep.CreateConfig(&config)
if err != nil {
logger.Warn(err)
return errorMsg
}
_ = so.Emit(
utils.ConfigSendConfigWhenConnected, config.Data.ToJSON(), func(so socketio.Socket, data string) {
logger.Debug("Client ACK with data: ", data)
},
)
return okMsg
}
func handleModuleDeclaration(so socketio.Socket, msg string) {
instanceUuid, moduleName, err := utils.ParseParameters(so.Request().URL.RawQuery)
if err != nil {
_ = so.Emit(utils.ErrorConnection, map[string]string{"error": err.Error()})
return
}
declaration := structure.BackendDeclaration{}
err = json.Unmarshal([]byte(msg), &declaration)
if err != nil {
_ = so.Emit(utils.ErrorConnection, map[string]string{"error": err.Error()})
logger.Warnf("handleModuleDeclaration: %s, error parse json data: %s", so.Id(), err.Error())
return
}
_, err = govalidator.ValidateStruct(declaration)
if err != nil {
errors := govalidator.ErrorsByField(err)
_ = so.Emit(utils.ErrorConnection, map[string]map[string]string{"error": errors})
logger.Warnf("SOCKET ROUTES ERROR, handleModuleDeclaration: %s, error validate routes data: %s", so.Id(), errors)
} else if backendRoutes.AddAddressOrUpdate(so.Id(), declaration) {
BroadcastRoutesSnapshot(instanceUuid)
discoverer := getOrRegisterDiscoverer(instanceUuid)
discoverer.BroadcastModuleAddresses(moduleName)
}
}
func onRequestConfig(so socketio.Socket) {
logger.Debugf("onRequestConfig: %s", so.Id())
instanceUuid, moduleName, err := utils.ParseParameters(so.Request().URL.RawQuery)
if err != nil {
_ = so.Emit(utils.ErrorConnection, map[string]string{"error": err.Error()})
return
}
config, err := service.GetConfig(instanceUuid, moduleName)
if err != nil {
_ = so.Emit(utils.ErrorConnection, map[string]string{"error": err.Error()})
return
}
_ = so.Emit(
utils.ConfigSendConfigOnRequest,
config.Data.ToJSON(),
func(so socketio.Socket, data string) {
logger.Debug("Client ACK with data: ", data)
},
)
}
+7
View File
@@ -0,0 +1,7 @@
package socket
func must(err error) {
if err != nil {
panic(err)
}
}
+110
View File
@@ -0,0 +1,110 @@
package socket
import (
"encoding/json"
"github.com/googollee/go-socket.io"
"github.com/integration-system/isp-lib/config"
"github.com/integration-system/isp-lib/logger"
str "github.com/integration-system/isp-lib/structure"
"github.com/integration-system/isp-lib/utils"
"isp-config-service/conf"
"isp-config-service/entity"
"isp-config-service/model"
"isp-config-service/service"
)
var (
server *socketio.Server
br *broadcaster
socketRoomStats = service.NewRoomStats()
backendRoutes = &service.RouterTables{}
ConfigServiceBackendDeclaration = &str.BackendDeclaration{}
)
func init() {
newServer, err := socketio.NewServer(nil)
if err != nil {
logger.Fatal(err)
}
sessionStore := service.NewSessionStore(service.WithOnRemoveCallback(func(id string) {
socketRoomStats.RemoveSocketConn(id)
}))
newServer.SetSessionManager(sessionStore)
newServer.SetAdaptor(socketRoomStats)
must(newServer.On("connection", onConnect))
must(newServer.On("disconnection", onDisconnect))
must(newServer.On("error", onError))
must(newServer.On(utils.ModuleSendRequirements, onReceivedModuleRequirements))
must(newServer.On(utils.ModuleReady, onReceiveModuleReady))
must(newServer.On(utils.ModuleSendConfigSchema, onReceiveRemoteConfigSchema))
must(newServer.On(utils.ModuleUpdateRoutes, onReceiveRoutesUpdate))
server = newServer
br = NewBroadcaster(server, 0)
}
func Get() *socketio.Server {
return server
}
func GetRoutes() *service.RouterTables {
return backendRoutes
}
func SetBackendMethods(backendConfig *str.BackendDeclaration) {
ConfigServiceBackendDeclaration = backendConfig
moduleName := config.Get().(*conf.Configuration).ModuleName
backendRoutes.AddAddressOrUpdate(moduleName, *ConfigServiceBackendDeclaration)
instances, err := model.InstanceRep.GetInstances(nil)
if err != nil {
logger.Warn("Error receiving instance from db", err)
} else {
for _, v := range instances {
BroadcastRoutesSnapshot(v.Uuid)
}
}
}
func GetRoomsCount() map[string]map[string]int {
return socketRoomStats.RoomsCount()
}
func GetModuleConnectionIdMapByInstanceId(instanceId string) map[string][]string {
return socketRoomStats.GetModuleConnectionMap()[instanceId]
}
func GetConnectionById(instanceId, sockId string) (*service.SocketConn, bool) {
return socketRoomStats.GetConnection(instanceId, sockId)
}
func SendNewConfig(instanceUuid string, moduleName string, config *entity.Config) {
moduleKey := instanceUuid + moduleName
br.BroadcastConfig(moduleKey, config.Data.ToJSON(), nil)
}
func SendRoutesSnapshot(so socketio.Socket) {
bytes, err := json.Marshal(backendRoutes.GetRoutes())
if err != nil {
logger.Warn("Error when serializing Backend Routes", err)
return
}
if err := so.Emit(utils.ConfigSendRoutesWhenConnected, string(bytes)); err != nil {
logger.Warn(err)
}
}
func BroadcastRoutesSnapshot(instanceUuid string) {
bytes, err := json.Marshal(backendRoutes.GetRoutes())
if err != nil {
logger.Warn("Error when serializing Backend Routes", err)
return
}
br.BroadcastRoutes(RoutesSubscribersRoom(instanceUuid), string(bytes), func(data interface{}) {
logger.Infof("Send %d routes", len(*backendRoutes.GetRoutes()))
logger.Debugf("Send Routes: %v", *backendRoutes.GetRoutes())
})
}
@@ -0,0 +1,134 @@
{
"swagger": "2.0",
"info": {
"title": "proto/backend_service.proto",
"version": "version not set"
},
"schemes": [
"http",
"https"
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"paths": {
"/api": {
"post": {
"summary": "===== MAIN REQUEST =====",
"operationId": "Request",
"responses": {
"200": {
"description": "",
"schema": {
"$ref": "#/definitions/ispMessage"
}
}
},
"parameters": [
{
"name": "Grpc-Metadata-proxy_method_name",
"in": "header",
"required": true,
"type": "string"
},
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/ispMessage"
}
}
],
"tags": [
"BackendService"
]
}
}
},
"definitions": {
"ispMessage": {
"type": "object",
"properties": {
"structBody": {
"$ref": "#/definitions/protobufStruct"
},
"listBody": {
"$ref": "#/definitions/protobufListValue"
},
"NullBody": {
"$ref": "#/definitions/protobufNullValue"
}
}
},
"protobufListValue": {
"type": "object",
"properties": {
"values": {
"type": "array",
"items": {
"$ref": "#/definitions/protobufValue"
},
"description": "Repeated field of dynamically typed values."
}
},
"description": "`ListValue` is a wrapper around a repeated field of values.\n\nThe JSON representation for `ListValue` is JSON array."
},
"protobufNullValue": {
"type": "string",
"enum": [
"NULL_VALUE"
],
"default": "NULL_VALUE",
"description": "`NullValue` is a singleton enumeration to represent the null value for the\n`Value` type union.\n\n The JSON representation for `NullValue` is JSON `null`.\n\n - NULL_VALUE: Null value."
},
"protobufStruct": {
"type": "object",
"properties": {
"fields": {
"type": "object",
"additionalProperties": {
"$ref": "#/definitions/protobufValue"
},
"description": "Unordered map of dynamically typed values."
}
},
"description": "`Struct` represents a structured data value, consisting of fields\nwhich map to dynamically typed values. In some languages, `Struct`\nmight be supported by a native representation. For example, in\nscripting languages like JS a struct is represented as an\nobject. The details of that representation are described together\nwith the proto support for the language.\n\nThe JSON representation for `Struct` is JSON object."
},
"protobufValue": {
"type": "object",
"properties": {
"null_value": {
"$ref": "#/definitions/protobufNullValue",
"description": "Represents a null value."
},
"number_value": {
"type": "number",
"format": "double",
"description": "Represents a double value."
},
"string_value": {
"type": "string",
"description": "Represents a string value."
},
"bool_value": {
"type": "boolean",
"format": "boolean",
"description": "Represents a boolean value."
},
"struct_value": {
"$ref": "#/definitions/protobufStruct",
"description": "Represents a structured value."
},
"list_value": {
"$ref": "#/definitions/protobufListValue",
"description": "Represents a repeated `Value`."
}
},
"description": "`Value` represents a dynamically typed value which can be either\nnull, a number, a string, a boolean, a recursive struct value, or a\nlist of values. A producer of value is expected to set one of that\nvariants, absence of any variant indicates an error.\n\nThe JSON representation for `Value` is JSON value."
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 445 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

+95
View File
@@ -0,0 +1,95 @@
<!-- HTML for static distribution bundle build -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Swagger UI</title>
<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,700|Source+Code+Pro:300,600|Titillium+Web:400,600,700" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="./swagger-ui.css" >
<link rel="icon" type="image/png" href="./favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="./favicon-16x16.png" sizes="16x16" />
<style>
html
{
box-sizing: border-box;
overflow: -moz-scrollbars-vertical;
overflow-y: scroll;
}
*,
*:before,
*:after
{
box-sizing: inherit;
}
body {
margin:0;
background: #fafafa;
}
</style>
</head>
<body>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="position:absolute;width:0;height:0">
<defs>
<symbol viewBox="0 0 20 20" id="unlocked">
<path d="M15.8 8H14V5.6C14 2.703 12.665 1 10 1 7.334 1 6 2.703 6 5.6V6h2v-.801C8 3.754 8.797 3 10 3c1.203 0 2 .754 2 2.199V8H4c-.553 0-1 .646-1 1.199V17c0 .549.428 1.139.951 1.307l1.197.387C5.672 18.861 6.55 19 7.1 19h5.8c.549 0 1.428-.139 1.951-.307l1.196-.387c.524-.167.953-.757.953-1.306V9.199C17 8.646 16.352 8 15.8 8z"></path>
</symbol>
<symbol viewBox="0 0 20 20" id="locked">
<path d="M15.8 8H14V5.6C14 2.703 12.665 1 10 1 7.334 1 6 2.703 6 5.6V8H4c-.553 0-1 .646-1 1.199V17c0 .549.428 1.139.951 1.307l1.197.387C5.672 18.861 6.55 19 7.1 19h5.8c.549 0 1.428-.139 1.951-.307l1.196-.387c.524-.167.953-.757.953-1.306V9.199C17 8.646 16.352 8 15.8 8zM12 8H8V5.199C8 3.754 8.797 3 10 3c1.203 0 2 .754 2 2.199V8z"/>
</symbol>
<symbol viewBox="0 0 20 20" id="close">
<path d="M14.348 14.849c-.469.469-1.229.469-1.697 0L10 11.819l-2.651 3.029c-.469.469-1.229.469-1.697 0-.469-.469-.469-1.229 0-1.697l2.758-3.15-2.759-3.152c-.469-.469-.469-1.228 0-1.697.469-.469 1.228-.469 1.697 0L10 8.183l2.651-3.031c.469-.469 1.228-.469 1.697 0 .469.469.469 1.229 0 1.697l-2.758 3.152 2.758 3.15c.469.469.469 1.229 0 1.698z"/>
</symbol>
<symbol viewBox="0 0 20 20" id="large-arrow">
<path d="M13.25 10L6.109 2.58c-.268-.27-.268-.707 0-.979.268-.27.701-.27.969 0l7.83 7.908c.268.271.268.709 0 .979l-7.83 7.908c-.268.271-.701.27-.969 0-.268-.269-.268-.707 0-.979L13.25 10z"/>
</symbol>
<symbol viewBox="0 0 20 20" id="large-arrow-down">
<path d="M17.418 6.109c.272-.268.709-.268.979 0s.271.701 0 .969l-7.908 7.83c-.27.268-.707.268-.979 0l-7.908-7.83c-.27-.268-.27-.701 0-.969.271-.268.709-.268.979 0L10 13.25l7.418-7.141z"/>
</symbol>
<symbol viewBox="0 0 24 24" id="jump-to">
<path d="M19 7v4H5.83l3.58-3.59L8 6l-6 6 6 6 1.41-1.41L5.83 13H21V7z"/>
</symbol>
<symbol viewBox="0 0 24 24" id="expand">
<path d="M10 18h4v-2h-4v2zM3 6v2h18V6H3zm3 7h12v-2H6v2z"/>
</symbol>
</defs>
</svg>
<div id="swagger-ui"></div>
<script src="./swagger-ui-bundle.js"> </script>
<script src="./swagger-ui-standalone-preset.js"> </script>
<script>
window.onload = function() {
// Build a system
const ui = SwaggerUIBundle({
url: "/swagger/config_service.swagger.json",
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
})
window.ui = ui
}
</script>
</body>
</html>
Loaded 100 of 124 files, more files were not shown because too many files have changed in this diff. Show more