Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c4ded39e7c | ||
|
|
c8518e9f35 | ||
|
|
97d3a38ed8 | ||
|
|
e840b53978 | ||
|
|
c43e52e9ad | ||
|
|
2a2bd99fcf | ||
|
|
c4f9fc4585 | ||
|
|
0222dfd865 | ||
|
|
11f91b67a8 | ||
|
|
6e2d485b90 | ||
|
|
e336a57e13 | ||
|
|
29e7c119bd | ||
|
|
882228558d | ||
|
|
51360e802f | ||
|
|
7a06660597 | ||
|
|
4553cd0261 | ||
|
|
2bbc426bef | ||
|
|
b22a22cac9 | ||
|
|
cc7b931e0a | ||
|
|
d4a44b0d72 | ||
|
|
284a9bb444 | ||
|
|
ef4dc0e972 | ||
|
|
def031958b | ||
|
|
00c1936683 | ||
|
|
cc3aab1e7b | ||
|
|
c14de6d198 | ||
|
|
f9f8186451 | ||
|
|
0259cf84ce | ||
|
|
04ceb5f4fa | ||
|
|
6efcbe7c70 | ||
|
|
e0ce92a9f3 | ||
|
|
28e08e108a | ||
|
|
4e68903251 | ||
|
|
73515e5179 | ||
|
|
f752770788 | ||
|
|
6eb6efe844 | ||
|
|
837b8755a0 | ||
|
|
e3b5e867b1 | ||
|
|
362efd9546 | ||
|
|
a958874731 | ||
|
|
0d5094cfb5 | ||
|
|
74b32e064e | ||
|
|
3ad5dfe030 | ||
|
|
95242965da | ||
|
|
8c15105087 | ||
|
|
db68505cca | ||
|
|
795aee86d1 | ||
|
|
33621ff523 | ||
|
|
415a694228 | ||
|
|
1fe8b7f78d | ||
|
|
c2fc3c54da | ||
|
|
652c2d95b8 | ||
|
|
da1b6caf67 | ||
|
|
deafdfb7ab | ||
|
|
f9feaeab0b | ||
|
|
330c160122 | ||
|
|
238c7b3a44 | ||
|
|
1317696cb7 | ||
|
|
23108f2224 | ||
|
|
6b14252577 | ||
|
|
8386cd7503 | ||
|
|
c6225eeb3a | ||
|
|
a12c2fd120 | ||
|
|
9e503ab31f | ||
|
|
c31abb84c9 | ||
|
|
b1a0bc252f | ||
|
|
599b1639e7 | ||
|
|
1199f9ae8e | ||
|
|
cb8ae318c4 | ||
|
|
fec8a759bc | ||
|
|
5d4b54c39c | ||
|
|
4ebab3a967 | ||
|
|
73315e6671 | ||
|
|
db03a888fb | ||
|
|
7d4a5c4c6c | ||
|
|
94397ea4c7 | ||
|
|
e05319432e | ||
|
|
f1bce695fb | ||
|
|
7aad2697f7 | ||
|
|
848a2d74d6 | ||
|
|
a2a470ad93 | ||
|
|
78150b2661 | ||
|
|
ed2e1a0936 | ||
|
|
445389b7d8 | ||
|
|
1bb8cbf3ab | ||
|
|
ca6fe7b86e | ||
|
|
0b351ea3a2 | ||
|
|
05c5db53bd | ||
|
|
7632e07f4e | ||
|
|
1ddbe43618 | ||
|
|
79f83e245c | ||
|
|
d678f28909 | ||
|
|
c3e95fa98c | ||
|
|
e32e55df15 | ||
|
|
48eaf48797 |
No files matched your search
+23
-6
@@ -1,9 +1,26 @@
|
||||
### v1.2.2
|
||||
* add migrations temp
|
||||
### v1.2.1
|
||||
* fix doc generate
|
||||
### v1.2.0
|
||||
* add method `GetSchemaByModuleId`
|
||||
### v2.1.1
|
||||
* update to new endpoint descriptor struct with extra fields introduced in isp-lib v2.1.0
|
||||
|
||||
### v2.1.0
|
||||
* fix panic type casting in shapshot
|
||||
* create empty default config now
|
||||
* add method `/module/get_by_name` to fetch module object by name
|
||||
|
||||
### 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.1.0
|
||||
* update libs
|
||||
* default config handling
|
||||
Generated
+311
-158
@@ -2,12 +2,23 @@
|
||||
|
||||
|
||||
[[projects]]
|
||||
digest = "1:e92f5581902c345eb4ceffdcd4a854fb8f73cf436d47d837d1ec98ef1fe0a214"
|
||||
name = "github.com/StackExchange/wmi"
|
||||
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"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "5d049714c4a64225c3c79a7cf7d02f7fb5b96338"
|
||||
version = "1.0.0"
|
||||
revision = "ec5e00d3c878b2a97bbe0884ef45ffd1b4f669f5"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:320e7ead93de9fd2b0e59b50fd92a4d50c1f8ab455d96bc2eb083267453a9709"
|
||||
@@ -17,6 +28,14 @@
|
||||
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"
|
||||
@@ -33,6 +52,70 @@
|
||||
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"
|
||||
@@ -41,17 +124,6 @@
|
||||
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"
|
||||
@@ -71,66 +143,67 @@
|
||||
version = "v8.0.6"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:b532ee3f683c057e797694b5bfeb3827d89e6adf41c53dbc80e549bca76364ea"
|
||||
digest = "1:07f4fafe81587b642166199f41c3edcca12929fcfcc0261b00be5dea2f968f44"
|
||||
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: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"
|
||||
digest = "1:0ade334594e69404d80d9d323445d2297ff8161637f9b2d347cc6973d2d6f05b"
|
||||
name = "github.com/hashicorp/errwrap"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "c8aeb1ed9b49d7de8fef8662efb18f1d289c5f2e"
|
||||
revision = "8a6fb523712970c966eefc6b39ed2c5e74880354"
|
||||
version = "v1.0.0"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:e62657cca9badaa308d86e7716083e4c5933bb78e30a17743fc67f50be26f6f4"
|
||||
name = "github.com/gorilla/websocket"
|
||||
digest = "1:cf6b61e1b4c26b0c7526cee4a0cee6d8302b17798af4b2a56a90eedac0aef11a"
|
||||
name = "github.com/hashicorp/go-hclog"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "c3e18be99d19e6b3e8f1559eea2c161a665c4b6b"
|
||||
version = "v1.4.1"
|
||||
revision = "5ccdce08c75b6c7b37af61159f13f6a4f5e2e928"
|
||||
version = "v0.9.2"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:99a9eab89cf8193a246811614678f34432e95446c34142594c450acb1a7a31cc"
|
||||
name = "github.com/grpc-ecosystem/grpc-gateway"
|
||||
packages = [
|
||||
"internal",
|
||||
"runtime",
|
||||
"utilities",
|
||||
]
|
||||
digest = "1:6e9806a06d00f4d1f90806d7b5cfb11e35dca76503390ca6e704b05ea7051bff"
|
||||
name = "github.com/hashicorp/go-immutable-radix"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "471f45a5a99a578de7a8638dc7ed29e245bde097"
|
||||
version = "v1.11.1"
|
||||
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"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:c0d19ab64b32ce9fe5cf4ddceba78d5bc9807f0016db6b1183599da3dcc24d10"
|
||||
@@ -151,6 +224,22 @@
|
||||
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"
|
||||
@@ -173,19 +262,22 @@
|
||||
revision = "ac5582987a2f25e8743e0ebb7259312adda05c23"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:9e2fd899fdb17e28e9d036fe7a604a1e04918aa4865d5a2150008fc12c6134be"
|
||||
name = "github.com/integration-system/golang-socketio"
|
||||
digest = "1:af0185228b5f1c08939721c26a61787c65d6d4cdd6ce5078d0bb86cb1d7a907a"
|
||||
name = "github.com/integration-system/isp-etp-go"
|
||||
packages = [
|
||||
".",
|
||||
"protocol",
|
||||
"transport",
|
||||
"ack",
|
||||
"bpool",
|
||||
"client",
|
||||
"gen",
|
||||
"parser",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "5959fcea049facd9441fff9de976191accd3cf9f"
|
||||
revision = "aab01a1b29ac06ebeb0216b9b43708491b8d5aee"
|
||||
version = "v2.0.2"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:c2cbe4bc2b4615c904b02e66538790b4b27e6637f9f414f35904c78b855fcf2d"
|
||||
digest = "1:194932f6894a42dd62acd1092c529befbe576abf50fe929a0e30ae3544ceb6ee"
|
||||
name = "github.com/integration-system/isp-lib"
|
||||
packages = [
|
||||
"backend",
|
||||
@@ -193,17 +285,39 @@
|
||||
"config",
|
||||
"config/schema",
|
||||
"database",
|
||||
"logger",
|
||||
"metric",
|
||||
"proto/stubs",
|
||||
"socket",
|
||||
"streaming",
|
||||
"structure",
|
||||
"utils",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "ec379c1305f381a22a2934d406f4e3c3e20ef0c2"
|
||||
version = "v1.6.2"
|
||||
revision = "4ea9449f1b3f2565b9038b0d4cdda3b02089aa8c"
|
||||
version = "v2.1.0"
|
||||
|
||||
[[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"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
@@ -213,6 +327,14 @@
|
||||
pruneopts = "UT"
|
||||
revision = "5475a8b08e62e41fa886641861ac225e7f91e4e5"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:965f8051786df58d7d62c8ffa2d90cb84000aab1a167e5c4713ff572cd7e164e"
|
||||
name = "github.com/integration-system/net-mux"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "9dc223fe46d293b528c8e2a04c43d991bc23a2de"
|
||||
version = "v1.0.0"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:01ed62f8f4f574d8aff1d88caee113700a2b44c42351943fa73cc1808f736a50"
|
||||
name = "github.com/jinzhu/inflection"
|
||||
@@ -222,18 +344,18 @@
|
||||
version = "v1.0.0"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:ac7f1061abc812a5d0de6df7e3f477cef942aef503848f436da0f0eb2603bfbf"
|
||||
digest = "1:d78015a9da26d37166a2119592019e8bfe9b24bec60aff4a46db6110070fb1b2"
|
||||
name = "github.com/json-iterator/go"
|
||||
packages = [
|
||||
".",
|
||||
"extra",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "27518f6661eba504be5a7a9a9f6d9460d892ade3"
|
||||
version = "v1.1.7"
|
||||
revision = "03217c3e97663914aec3faafde50d081f197a0a2"
|
||||
version = "1.1.8"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:caa1da085cc12cd39d3ddb267434902f621050e1b46f7e9477b2b933df680193"
|
||||
digest = "1:acfc228fb5fbfb82645c121e3224bd546ed68aef6dfc87f63e2d8de099a3822b"
|
||||
name = "github.com/klauspost/compress"
|
||||
packages = [
|
||||
"flate",
|
||||
@@ -241,16 +363,8 @@
|
||||
"zlib",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "fdc46f09595ea8241b9bfe291bbc868a7af19e10"
|
||||
version = "v1.8.2"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:923c4d7194b42e054b2eb8a6c62824ac55e23ececc1c7e48d4da69c971c55954"
|
||||
name = "github.com/klauspost/cpuid"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "05a8198c0f5a27739aec358908d7e12c64ce6eb7"
|
||||
version = "v1.2.1"
|
||||
revision = "a41f1a10bd3b167958ff6df80b800fe2969dd3ca"
|
||||
version = "v1.9.0"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:31e761d97c76151dde79e9d28964a812c46efc5baee4085b86f68f0c654450de"
|
||||
@@ -280,30 +394,6 @@
|
||||
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"
|
||||
@@ -337,12 +427,20 @@
|
||||
revision = "c48cc78d482608239f6c4c92a4abd87eb8761c90"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:93131d8002d7025da13582877c32d1fc302486775a1b06f62241741006428c5e"
|
||||
digest = "1:ee4d4af67d93cc7644157882329023ce9a7bcfce956a079069a9405521c7cc8d"
|
||||
name = "github.com/opencontainers/go-digest"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "279bed98673dd5bef374d3b6e4b09e2af76183bf"
|
||||
version = "v1.0.0-rc1"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:bbd3997f0121200f72b64d7a3826eb8a0b910d6a4c19894c9fe2852b9e5eaf3b"
|
||||
name = "github.com/pelletier/go-toml"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "728039f679cbcd4f6a54e080d2219a4c4928c546"
|
||||
version = "v1.4.0"
|
||||
revision = "8fe62057ea2d46ce44254c98e84e810044dbe197"
|
||||
version = "v1.5.0"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:cf31692c14422fa27c83a05292eb5cbe0fb2775972e8f1f8446a71549bd8980b"
|
||||
@@ -352,6 +450,14 @@
|
||||
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"
|
||||
@@ -369,15 +475,12 @@
|
||||
revision = "cac0b30c2563378d434b5af411844adff8e32960"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:ab1672baf07ee80c988e369e5633bcac459342e8e00d0c38a799056395fe9dba"
|
||||
name = "github.com/shirou/gopsutil"
|
||||
packages = [
|
||||
"cpu",
|
||||
"internal/common",
|
||||
]
|
||||
digest = "1:274f67cb6fed9588ea2521ecdac05a6d62a8c51c074c1fccc6a49a40ba80e925"
|
||||
name = "github.com/satori/go.uuid"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "e4ec7b275ada47ca32799106c2dba142d96aaf93"
|
||||
version = "v2.19.8"
|
||||
revision = "f58768cc1a7a7e77a3bd49e98cdd21419399b6a3"
|
||||
version = "v1.2.0"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:04457f9f6f3ffc5fea48e71d62f2ca256637dee0a04d710288e27e05c8b41976"
|
||||
@@ -415,21 +518,37 @@
|
||||
version = "v1.1.0"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:c1b1102241e7f645bc8e0c22ae352e8f0dc6484b6cb4d132fa9f24174e0119e2"
|
||||
digest = "1:524b71991fc7d9246cc7dc2d9e0886ccb97648091c63e30eef619e6862c955dd"
|
||||
name = "github.com/spf13/pflag"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "298182f68c66c05229eb03ac171abe6e309ee79a"
|
||||
version = "v1.0.3"
|
||||
revision = "2e9d26c8c37aae03e3f9d4e90b7116f5accb7cab"
|
||||
version = "v1.0.5"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:11118bd196646c6515fea3d6c43f66162833c6ae4939bfb229b9956d91c6cf17"
|
||||
digest = "1:0b60fc944fb6a7b6c985832bd341bdb7ed8fe894fea330414e7774bb24652962"
|
||||
name = "github.com/spf13/viper"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "b5bf975e5823809fb22c7644d008757f78a4259e"
|
||||
revision = "72b022eb357a56469725dcd03918449e2278d02e"
|
||||
version = "v1.5.0"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:8548c309c65a85933a625be5e7d52b6ac927ca30c56869fae58123b8a77a75e1"
|
||||
name = "github.com/stretchr/testify"
|
||||
packages = ["assert"]
|
||||
pruneopts = "UT"
|
||||
revision = "221dbe5ed46703ee255b1da0dec05086f5035f62"
|
||||
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"
|
||||
@@ -448,7 +567,7 @@
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:b97ba937497c9b282245aa8f633212c96fcaa1b4cc30e9ab6ae41a0168e32c35"
|
||||
digest = "1:77f7e2f75e4c44ede24f47aca6c514f24f06c6a0ee3c47c8d7ce2b77b49ac482"
|
||||
name = "github.com/valyala/fasthttp"
|
||||
packages = [
|
||||
".",
|
||||
@@ -456,53 +575,69 @@
|
||||
"stackless",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "8713335f548d2c18effe36c9686f5a88b65eefce"
|
||||
revision = "9bc6da12192c610a272a9289b9574eb5d8cfdfe1"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:39a425f98fb19427061a693fe6bf0683c9bddec4b25b17067e34fdb465e39cb9"
|
||||
name = "github.com/x-cray/logrus-prefixed-formatter"
|
||||
branch = "master"
|
||||
digest = "1:87fe9bca786484cef53d52adeec7d1c52bc2bfbee75734eddeb75fc5c7023871"
|
||||
name = "github.com/xeipuuv/gojsonpointer"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "bb2702d423886830dee131692131d35648c382e2"
|
||||
version = "v0.5.2"
|
||||
revision = "02993c407bfbf5f6dae44c4f4b1cf6a39b5fc5bb"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:35ce874cf16f78a2da908ab28b0277497e36603d289db00d39da5200bc8ace08"
|
||||
name = "golang.org/x/crypto"
|
||||
packages = [
|
||||
"pbkdf2",
|
||||
"ssh/terminal",
|
||||
]
|
||||
digest = "1:dc6a6c28ca45d38cfce9f7cb61681ee38c5b99ec1425339bfc1e1a7ba769c807"
|
||||
name = "github.com/xeipuuv/gojsonreference"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "9756ffdc24725223350eb3266ffb92590d28f278"
|
||||
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:8c8471f63317e39731853a4f55d5d8ff43a142aa425a666a0554bdba0a8b7f8b"
|
||||
digest = "1:f92f6956e4059f6a3efc14924d2dd58ba90da25cc57fe07ae3779ef2f5e0c5f2"
|
||||
name = "golang.org/x/crypto"
|
||||
packages = ["pbkdf2"]
|
||||
pruneopts = "UT"
|
||||
revision = "87dc89f01550277dc22b74ffcf4cd89fa2f40f4c"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:60dc5bc60f5ec42121f8b90de6f86bd1f708b6422114a02012395d43e377e757"
|
||||
name = "golang.org/x/net"
|
||||
packages = [
|
||||
"context",
|
||||
"context/ctxhttp",
|
||||
"http/httpguts",
|
||||
"http2",
|
||||
"http2/hpack",
|
||||
"idna",
|
||||
"internal/socks",
|
||||
"internal/timeseries",
|
||||
"proxy",
|
||||
"trace",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "ba9fcec4b297b415637633c5a6e8fa592e4a16c3"
|
||||
revision = "ec77196f6094c3492a8b61f2c11cf937f78992ae"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:4f9cc50343843f7c58c1a1aecf17c226ea0e855f4d3293e796701ae985111e0d"
|
||||
digest = "1:de0084adc1c0b8cf6fd192d7785b098b155ba355cbeec9ee361aea55b887ab9d"
|
||||
name = "golang.org/x/sys"
|
||||
packages = [
|
||||
"unix",
|
||||
"windows",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "749cb33beabd9aa6d3178e3de05bcc914f70b2bf"
|
||||
revision = "53bf42e6b339f7ed00535fc6915737b3959eac89"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:8d8faad6b12a3a4c819a3f9618cb6ee1fa1cfc33253abeeea8b55336721e3405"
|
||||
@@ -531,20 +666,17 @@
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:08aa0c3a326b71c5afe441683697766f6b172f652b919ecd114881a7f7581a4d"
|
||||
digest = "1:a910255c3b706b4d8f2b185ed6b40c8f31b805111be240def2bdf2c62b87591b"
|
||||
name = "google.golang.org/genproto"
|
||||
packages = [
|
||||
"googleapis/api/annotations",
|
||||
"googleapis/api/httpbody",
|
||||
"googleapis/rpc/errdetails",
|
||||
"googleapis/rpc/status",
|
||||
"protobuf/field_mask",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "92dd089d5514cecde7a465f807541f83dfd486d5"
|
||||
revision = "548a555dbc03994223efbaba0090152849259498"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:3b97661db2e5d4c87f7345e875ea28f911e54c715ba0a74be08e1649d67e05cd"
|
||||
digest = "1:6cd77d0b616d2dcebd363dfecba593f27b0151fc82cdb5fbfb96c5a7cfbc95b5"
|
||||
name = "google.golang.org/grpc"
|
||||
packages = [
|
||||
".",
|
||||
@@ -582,16 +714,16 @@
|
||||
"tap",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "6eaf6f47437a6b4e2153a190160ef39a92c7eceb"
|
||||
version = "v1.23.0"
|
||||
revision = "f6d0f9ee430895e87ef1ceb5ac8f39725bafceef"
|
||||
version = "v1.24.0"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:4d2e5a73dc1500038e504a8d78b986630e3626dc027bc030ba5c75da257cdb96"
|
||||
digest = "1:59f10c1537d2199d9115d946927fe31165959a95190849c82ff11e05803528b0"
|
||||
name = "gopkg.in/yaml.v2"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "51d6538a90f86fe93ac480b35f37b2be17fef232"
|
||||
version = "v2.2.2"
|
||||
revision = "f221b8435cfb71e54062f6c6e99e9ade30b124d5"
|
||||
version = "v2.2.4"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:999d566ad1ae4303c456af5a155f7b42401cca4fd33552567ed9dd997b107a08"
|
||||
@@ -602,6 +734,18 @@
|
||||
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
|
||||
@@ -609,28 +753,37 @@
|
||||
"github.com/asaskevich/govalidator",
|
||||
"github.com/cenkalti/backoff",
|
||||
"github.com/go-pg/pg",
|
||||
"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/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/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/valyala/fasthttp",
|
||||
"golang.org/x/net/context",
|
||||
"google.golang.org/genproto/googleapis/api/annotations",
|
||||
"github.com/integration-system/isp-log",
|
||||
"github.com/integration-system/isp-log/stdcodes",
|
||||
"github.com/integration-system/net-mux",
|
||||
"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",
|
||||
"google.golang.org/grpc",
|
||||
"google.golang.org/grpc/codes",
|
||||
"google.golang.org/grpc/grpclog",
|
||||
"google.golang.org/grpc/status",
|
||||
]
|
||||
solver-name = "gps-cdcl"
|
||||
|
||||
+2
-6
@@ -37,9 +37,5 @@
|
||||
branch = "master"
|
||||
|
||||
[[override]]
|
||||
name = "github.com/googollee/go-socket.io"
|
||||
revision = "c8aeb1ed9b49d7de8fef8662efb18f1d289c5f2e"
|
||||
|
||||
[[override]]
|
||||
name = "github.com/googollee/go-engine.io"
|
||||
revision = "e2f255711dcb2ea41e42c6d9d98c172d7edf6509"
|
||||
name = "github.com/hashicorp/raft"
|
||||
branch = "master"
|
||||
@@ -1,92 +0,0 @@
|
||||
## 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
|
||||
@@ -0,0 +1,187 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
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()
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
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,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
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())
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
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
|
||||
)
|
||||
+13
-4
@@ -1,15 +1,15 @@
|
||||
database:
|
||||
address: "127.0.0.1"
|
||||
schema: "config_service"
|
||||
database: "isp"
|
||||
database: "test"
|
||||
port: "5432"
|
||||
username: "isp"
|
||||
password: "isp_password"
|
||||
username: "test"
|
||||
password: "password"
|
||||
createSchema: true
|
||||
|
||||
moduleName: "config"
|
||||
grpcOuterAddress:
|
||||
ip: 127.0.0.1
|
||||
ip: ""
|
||||
port: 9002
|
||||
|
||||
ws:
|
||||
@@ -28,3 +28,12 @@ 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
|
||||
@@ -0,0 +1,10 @@
|
||||
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
|
||||
+19
-6
@@ -5,12 +5,25 @@ import (
|
||||
)
|
||||
|
||||
type Configuration struct {
|
||||
Database structure.DBConfiguration `valid:"required~Required"`
|
||||
Database structure.DBConfiguration `valid:"required~Required" schema:"База данных,настройка параметров подключения к базе данных"`
|
||||
GrpcOuterAddress structure.AddressConfiguration `valid:"required~Required" json:"grpcOuterAddress"`
|
||||
ModuleName string `valid:"required~Required"`
|
||||
WS struct {
|
||||
Rest structure.AddressConfiguration `valid:"required~Required"`
|
||||
Grpc structure.AddressConfiguration `valid:"required~Required"`
|
||||
}
|
||||
Metrics structure.MetricConfiguration
|
||||
WS WebService `valid:"required~Required" schema:"Конфигурация веб сервиса"`
|
||||
Metrics structure.MetricConfiguration
|
||||
Cluster ClusterConfiguration `valid:"required~Required"`
|
||||
}
|
||||
|
||||
type ClusterConfiguration struct {
|
||||
InMemory bool `schema:"Хранить логи и снэпшоты только в памяти"`
|
||||
BootstrapCluster bool `schema:"Поднимать кластер и объявлять лидером"`
|
||||
DataDir string `valid:"required~Required" 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:"Максимальное количество килобайт на чтение по вебсокету,при превышении соединение закрывается с ошибкой"`
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"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
|
||||
attemptTimeout = 300 * time.Millisecond
|
||||
|
||||
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.WithLogger(NewWriteLogger(strconv.Itoa(i)+"_config:", ioutil.Discard, "Apply 10 command")),
|
||||
//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, attemptTimeout)
|
||||
if !a.NoError(err) {
|
||||
return nil
|
||||
}
|
||||
log.Println("waiting until grpc ready:", time.Since(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, attemptTimeout)
|
||||
log.Println("waiting until raft ready:", time.Since(start).Round(time.Second))
|
||||
return a.NoError(err)
|
||||
}
|
||||
|
||||
func getRoutes(client *backend.InternalGrpcClient, a *assert.Assertions) []structure.BackendDeclaration {
|
||||
var response []structure.BackendDeclaration
|
||||
var err error
|
||||
f := func() (interface{}, error) {
|
||||
err = client.Invoke(
|
||||
getRoutesCommand,
|
||||
-1,
|
||||
nil,
|
||||
&response,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
} else if len(response) == 0 {
|
||||
return nil, errors.New("zero routes")
|
||||
}
|
||||
|
||||
//log.Println("routes:", response)
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
_, _ = await(f, time.Second, 50*time.Millisecond)
|
||||
a.NoError(err)
|
||||
return response
|
||||
}
|
||||
|
||||
func await(dialer func() (interface{}, error), timeout, attemptTimeout time.Duration) (interface{}, error) {
|
||||
retryer := utils.NewRetryer(dialer, timeout)
|
||||
retryer.AttemptTimeout = attemptTimeout
|
||||
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}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
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,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
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 (
|
||||
module *entity.Module
|
||||
config *entity.Config
|
||||
)
|
||||
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
|
||||
module = state.Modules().GetByName(request.ModuleName)
|
||||
if module != nil {
|
||||
config = state.Configs().GetActiveByModuleId(module.Id)
|
||||
}
|
||||
})
|
||||
if module == nil {
|
||||
return nil, status.Errorf(codes.NotFound, "module with name '%s' not found", request.ModuleName)
|
||||
}
|
||||
if config == nil {
|
||||
return nil, status.Errorf(codes.NotFound, "active config for module '%s' not found", request.ModuleName)
|
||||
}
|
||||
return config, 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,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"google.golang.org/grpc/status"
|
||||
"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"
|
||||
|
||||
"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
|
||||
}
|
||||
|
||||
// GetModuleByName godoc
|
||||
// @Summary Метод получения модуля по имени
|
||||
// @Description Модуль
|
||||
// @Tags Модули
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.GetByModuleNameRequest true "название модуля"
|
||||
// @Success 200 {object} entity.Module
|
||||
// @Failure 500 {object} structure.GrpcError
|
||||
// @Failure 404 {object} structure.GrpcError "модуль с указанным названием не найден"
|
||||
// @Router /module/get_by_name [POST]
|
||||
func (c *module) GetModuleByName(req domain.GetByModuleNameRequest) (*entity.Module, error) {
|
||||
var module *entity.Module
|
||||
c.rstore.VisitReadonlyState(func(readonlyState state.ReadonlyState) {
|
||||
module = readonlyState.Modules().GetByName(req.ModuleName)
|
||||
})
|
||||
if module == nil {
|
||||
return nil, status.Errorf(codes.NotFound, "module with name '%s' not found", req.ModuleName)
|
||||
}
|
||||
return module, nil
|
||||
}
|
||||
|
||||
func NewModule(rstore *store.Store) *module {
|
||||
return &module{
|
||||
rstore: rstore,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
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,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
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,
|
||||
}
|
||||
}
|
||||
@@ -1,169 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
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)
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
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)
|
||||
})
|
||||
*/
|
||||
@@ -1,133 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
+1036
File diff suppressed because it is too large.
Load diff
+17
-11
@@ -1,19 +1,25 @@
|
||||
package domain
|
||||
|
||||
type IdentitiesRequest struct {
|
||||
Ids []int32 `json:"ids" valid:"required~Required"`
|
||||
import "isp-config-service/entity"
|
||||
|
||||
type ConfigIdRequest struct {
|
||||
Id string `json:"id" valid:"required~Required"`
|
||||
}
|
||||
|
||||
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 CompileConfigsRequest struct {
|
||||
Data map[string]interface{}
|
||||
CommonConfigsIdList []string
|
||||
}
|
||||
|
||||
type GetByModuleIdRequest struct {
|
||||
ModuleId int32 `valid:"required~Required"`
|
||||
ModuleId string `valid:"required~Required"`
|
||||
}
|
||||
|
||||
type GetByModuleNameRequest struct {
|
||||
ModuleName string `valid:"required~Required"`
|
||||
}
|
||||
|
||||
type CreateUpdateConfigRequest struct {
|
||||
entity.Config
|
||||
Unsafe bool
|
||||
}
|
||||
+33
-16
@@ -1,34 +1,51 @@
|
||||
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 Connection struct {
|
||||
LibVersion string
|
||||
Version string
|
||||
Address structure.AddressConfiguration
|
||||
Endpoints []structure.EndpointConfig `json:",omitempty"`
|
||||
EstablishedAt time.Time
|
||||
}
|
||||
|
||||
type ModuleInfo struct {
|
||||
Id int32
|
||||
Id string
|
||||
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"`
|
||||
Configs []ConfigModuleInfo `json:",omitempty"`
|
||||
ConfigSchema *schema.Schema `json:",omitempty"`
|
||||
Status []Connection `json:",omitempty"`
|
||||
}
|
||||
|
||||
type Connection struct {
|
||||
LibVersion string
|
||||
Version string
|
||||
Address structure.AddressConfiguration
|
||||
Endpoints []structure.EndpointDescriptor `json:",omitempty"`
|
||||
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
|
||||
}
|
||||
+19
-17
@@ -1,39 +1,41 @@
|
||||
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{}
|
||||
|
||||
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 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"`
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Id int64 `json:"id"`
|
||||
type CommonConfig struct {
|
||||
tableName string `sql:"?db_schema.common_configs" json:"-"`
|
||||
Id string `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 {
|
||||
Id int32
|
||||
tableName string `sql:"?db_schema.config_schemas" json:"-"`
|
||||
Id string `json:"id"`
|
||||
Version string
|
||||
ModuleId int32
|
||||
ModuleId string
|
||||
Schema schema.Schema
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
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"`
|
||||
}
|
||||
+3
-11
@@ -1,20 +1,12 @@
|
||||
package entity
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
import "time"
|
||||
|
||||
type Module struct {
|
||||
Id int32 `json:"id"`
|
||||
InstanceId int32 `json:"instanceId" valid:"required~Required"`
|
||||
tableName string `sql:"?db_schema.modules" json:"-"`
|
||||
Id string `json:"id"`
|
||||
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"`
|
||||
}
|
||||
@@ -1,257 +0,0 @@
|
||||
// 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,
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
// 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
|
||||
)
|
||||
+30
-37
@@ -2,35 +2,31 @@ package helper
|
||||
|
||||
import (
|
||||
"github.com/integration-system/isp-lib/structure"
|
||||
"isp-config-service/controllers"
|
||||
"isp-config-service/controller"
|
||||
"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 =====
|
||||
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"`
|
||||
|
||||
DeleteModules func(identities []string) (*domain.DeleteResponse, error) `method:"delete_module" group:"module" inner:"true"`
|
||||
GetModulesInfo func() ([]domain.ModuleInfo, error) `method:"get_modules_info" group:"module" inner:"true"`
|
||||
GetModuleByName func(req domain.GetByModuleNameRequest) (*entity.Module, error) `method:"get_by_name" group:"module" inner:"true"`
|
||||
// ===== CONFIG =====
|
||||
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"`
|
||||
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"`
|
||||
|
||||
// ===== ROUTING =====
|
||||
GetRoutes func() (map[string]interface{}, error) `method:"get_routes" group:"routing" inner:"true"`
|
||||
GetRoutes func() ([]structure.BackendDeclaration, 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"`
|
||||
@@ -38,26 +34,23 @@ type Handlers struct {
|
||||
|
||||
func GetHandlers() *Handlers {
|
||||
return &Handlers{
|
||||
GetInstances: controllers.GetInstances,
|
||||
CreateUpdateInstance: controllers.CreateUpdateInstance,
|
||||
DeleteInstance: controllers.DeleteInstance,
|
||||
DeleteModules: controller.Module.DeleteModules,
|
||||
GetModulesInfo: controller.Module.GetModulesAggregatedInfo,
|
||||
GetModuleByName: controller.Module.GetModuleByName,
|
||||
|
||||
GetModules: controllers.GetModules,
|
||||
GetActiveModules: controllers.GetActiveModules,
|
||||
GetConnectedModules: controllers.GetConnectedModules,
|
||||
CreateUpdateModule: controllers.CreateUpdateModule,
|
||||
DeleteModule: controllers.DeleteModule,
|
||||
GetModulesInfo: controllers.GetModulesAggregatedInfo,
|
||||
GetActiveConfigByModuleName: controller.Config.GetActiveConfigByModuleName,
|
||||
CreateUpdateConfig: controller.Config.CreateUpdateConfig,
|
||||
MarkConfigAsActive: controller.Config.MarkConfigAsActive,
|
||||
DeleteConfig: controller.Config.DeleteConfigs,
|
||||
|
||||
GetConfigs: controllers.GetConfigs,
|
||||
GetConfigByInstanceUUIDAndModuleName: controllers.GetConfigByInstanceUUIDAndModuleName,
|
||||
CreateUpdateConfig: controllers.CreateUpdateConfig,
|
||||
UpdateActiveConfigByInstanceUUIDAndModuleName: controllers.UpdateActiveConfigByInstanceUUIDAndModuleName,
|
||||
MarkConfigAsActive: controllers.MarkConfigAsActive,
|
||||
DeleteConfig: controllers.DeleteConfig,
|
||||
GetCommonConfigs: controller.CommonConfig.GetConfigs,
|
||||
CreateUpdateCommonConfig: controller.CommonConfig.CreateUpdateConfig,
|
||||
DeleteCommonConfig: controller.CommonConfig.DeleteConfigs,
|
||||
CompileConfigs: controller.CommonConfig.CompileConfigs,
|
||||
GetLinks: controller.CommonConfig.GetLinks,
|
||||
|
||||
GetRoutes: controllers.GetRoutes,
|
||||
GetRoutes: controller.Routes.GetRoutes,
|
||||
|
||||
GetSchemaByModuleId: controllers.Schema.GetByModuleId,
|
||||
GetSchemaByModuleId: controller.Schema.GetByModuleId,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
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
|
||||
)
|
||||
@@ -1,242 +1,224 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"github.com/integration-system/isp-lib/bootstrap"
|
||||
"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"
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/integration-system/isp-etp-go"
|
||||
"github.com/integration-system/isp-lib/backend"
|
||||
"github.com/integration-system/isp-lib/bootstrap"
|
||||
"github.com/integration-system/isp-lib/config"
|
||||
"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"
|
||||
log "github.com/integration-system/isp-log"
|
||||
mux "github.com/integration-system/net-mux"
|
||||
"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/raft"
|
||||
"isp-config-service/service"
|
||||
"isp-config-service/store"
|
||||
"isp-config-service/store/state"
|
||||
"isp-config-service/subs"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
)
|
||||
|
||||
const (
|
||||
routerModule = "router"
|
||||
converterModule = "converter"
|
||||
moduleName = "config"
|
||||
defaultWsConnectionReadLimit int64 = 4 << 20 // 4 MB
|
||||
)
|
||||
|
||||
var (
|
||||
configData *conf.Configuration
|
||||
echoEndpoint *string
|
||||
version = "0.1.0"
|
||||
date = "undefined"
|
||||
version = "0.1.0"
|
||||
date = "undefined"
|
||||
|
||||
shutdownChan = make(chan struct{})
|
||||
muxer mux.Mux
|
||||
)
|
||||
|
||||
func init() {
|
||||
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
|
||||
config.InitConfig(&conf.Configuration{})
|
||||
if utils.LOG_LEVEL != "" {
|
||||
_ = log.SetLevel(utils.LOG_LEVEL)
|
||||
}
|
||||
}
|
||||
|
||||
// @title ISP configuration service
|
||||
// @version 1.2.0
|
||||
// @version 2.0.0
|
||||
// @description Сервис управления конфигурацией модулей ISP кластера
|
||||
|
||||
// @license.name GNU GPL v3.0
|
||||
|
||||
// @host localhost:9003
|
||||
// @BasePath /api/config
|
||||
|
||||
//go:generate swag init --parseVendor
|
||||
//go:generate rm -f docs/docs.go docs/swagger.json
|
||||
func main() {
|
||||
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)
|
||||
}
|
||||
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.
|
||||
ctx := context.Background()
|
||||
cfg := config.Get().(*conf.Configuration)
|
||||
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,
|
||||
endpoints := backend.GetEndpoints(cfg.ModuleName, handlers)
|
||||
address := cfg.GrpcOuterAddress
|
||||
if address.IP == "" {
|
||||
ip, err := getOutboundIP()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
address.IP = ip
|
||||
}
|
||||
declaration := structure.BackendDeclaration{
|
||||
ModuleName: cfg.ModuleName,
|
||||
Version: version,
|
||||
LibVersion: bootstrap.LibraryVersion,
|
||||
Endpoints: enndpoints,
|
||||
Address: addrOuter,
|
||||
})
|
||||
logger.Infof("EXPORTED MODULE METHODS: %v, module_name: %s, version: %s",
|
||||
enndpoints, configData.ModuleName, version)
|
||||
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
|
||||
}
|
||||
|
||||
// Start a HTTP server.
|
||||
func createRestServer(opts ...runtime.ServeMuxOption) {
|
||||
|
||||
mux := http.NewServeMux()
|
||||
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...)
|
||||
func initMultiplexer(addressConfiguration structure.AddressConfiguration) (net.Listener, net.Listener, error) {
|
||||
outerAddr, err := net.ResolveTCPAddr("tcp4", addressConfiguration.GetAddress())
|
||||
if err != nil {
|
||||
logger.Fatalf("failed to serve: %v", err)
|
||||
return nil, nil, fmt.Errorf("resolve outer address: %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.
|
||||
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 := srv.ListenAndServe(); err != nil {
|
||||
logger.Fatal(err)
|
||||
if err := muxer.Serve(); err != nil {
|
||||
log.Fatalf(codes.InitMuxError, "serve mux: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
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)
|
||||
return httpListener, raftListener, nil
|
||||
}
|
||||
|
||||
func handleModulesRequest(ctx *fasthttp.RequestCtx) {
|
||||
instances, err := model.InstanceRep.GetInstances(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()
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/isp-etp/", etpServer.ServeHttp)
|
||||
httpServer := &http.Server{Handler: mux}
|
||||
go func() {
|
||||
if err := httpServer.Serve(listener); err != nil && err != http.ErrServerClosed {
|
||||
log.Fatalf(codes.StartHttpServerError, "http server closed: %v", err)
|
||||
}
|
||||
}()
|
||||
holder.EtpServer = etpServer
|
||||
holder.HTTPServer = httpServer
|
||||
}
|
||||
|
||||
func initRaft(listener net.Listener, clusterCfg conf.ClusterConfiguration, declaration structure.BackendDeclaration) (*cluster.Client, *store.Store) {
|
||||
raftState, err := store.NewStateFromRepository()
|
||||
if err != nil {
|
||||
logger.Warn(err)
|
||||
ctx.Error("internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
log.Fatal(codes.RestoreFromRepositoryError, err)
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
result := make(map[string][]*domain.ModuleInfo, len(instances))
|
||||
for _, i := range instances {
|
||||
info, err := module.GetAggregatedModuleInfo(i.Uuid)
|
||||
if err != nil {
|
||||
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
|
||||
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 occurred
|
||||
}
|
||||
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
|
||||
if err != nil {
|
||||
log.Errorf(codes.BootstrapClusterError, "bootstrap cluster. %v", err)
|
||||
}
|
||||
|
||||
result[i.Uuid] = info
|
||||
}
|
||||
|
||||
if bytes, err := utils.ConvertGoToBytes(result); err != nil {
|
||||
logger.Warn(err)
|
||||
ctx.Error("internal server error", http.StatusInternalServerError)
|
||||
} else {
|
||||
ctx.SetStatusCode(http.StatusOK)
|
||||
ctx.SetContentType("application/json; charset=utf-8")
|
||||
ctx.SetBody(bytes)
|
||||
}
|
||||
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)
|
||||
} else {
|
||||
log.Info(codes.ShutdownHttpServerInfo, "http server shutdown success")
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
-- +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;
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
-- +goose Up
|
||||
CREATE schema if NOT EXISTS "config_service";
|
||||
|
||||
-- +goose Down
|
||||
DROP schema if EXISTS config_service CASCADE;
|
||||
@@ -1,47 +0,0 @@
|
||||
-- +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;
|
||||
@@ -1,24 +0,0 @@
|
||||
-- +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;
|
||||
@@ -1,70 +0,0 @@
|
||||
-- +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;
|
||||
@@ -1,6 +0,0 @@
|
||||
-- +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
|
||||
@@ -1,10 +0,0 @@
|
||||
-- +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);
|
||||
@@ -1,11 +0,0 @@
|
||||
-- +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);
|
||||
@@ -1,124 +0,0 @@
|
||||
-- +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)
|
||||
|
||||
@@ -1,127 +0,0 @@
|
||||
-- +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)
|
||||
@@ -1,9 +0,0 @@
|
||||
-- +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;
|
||||
@@ -1,23 +0,0 @@
|
||||
-- +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;
|
||||
@@ -1,42 +0,0 @@
|
||||
-- +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
|
||||
@@ -1,88 +0,0 @@
|
||||
-- +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
|
||||
@@ -1,27 +0,0 @@
|
||||
-- +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
|
||||
@@ -1,88 +0,0 @@
|
||||
-- +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
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
-- +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
|
||||
|
||||
@@ -1,117 +0,0 @@
|
||||
-- +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
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
-- +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
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
-- +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
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
-- +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
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
-- +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
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
-- +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
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
-- +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
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
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}
|
||||
)
|
||||
@@ -0,0 +1,54 @@
|
||||
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
|
||||
}
|
||||
+36
-78
@@ -1,96 +1,54 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"isp-config-service/entity"
|
||||
|
||||
"github.com/go-pg/pg"
|
||||
"github.com/go-pg/pg/orm"
|
||||
"github.com/integration-system/isp-lib/database"
|
||||
"isp-config-service/entity"
|
||||
)
|
||||
|
||||
type ConfigRepository struct {
|
||||
DB orm.DB
|
||||
type ConfigRepository interface {
|
||||
Snapshot() ([]entity.Config, error)
|
||||
Upsert(config entity.Config) (*entity.Config, error)
|
||||
Delete(identities []string) (int, error)
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
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()
|
||||
})
|
||||
return configs, 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()
|
||||
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
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return res, nil
|
||||
return &config, 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
|
||||
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
|
||||
}
|
||||
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
|
||||
return res.RowsAffected(), err
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
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
|
||||
}
|
||||
+35
-123
@@ -1,141 +1,53 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"isp-config-service/entity"
|
||||
|
||||
"github.com/go-pg/pg"
|
||||
|
||||
"github.com/go-pg/pg/orm"
|
||||
"time"
|
||||
"github.com/integration-system/isp-lib/database"
|
||||
"isp-config-service/entity"
|
||||
)
|
||||
|
||||
type ModulesRepository struct {
|
||||
DB orm.DB
|
||||
type ModulesRepository interface {
|
||||
Snapshot() ([]entity.Module, error)
|
||||
Upsert(module entity.Module) (*entity.Module, error)
|
||||
Delete(identities []string) (int, error)
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
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()
|
||||
})
|
||||
return modules, err
|
||||
}
|
||||
|
||||
func (r *ModulesRepository) GetModule(identity int32) (*entity.Module, error) {
|
||||
var module entity.Module
|
||||
var err = r.DB.Model(&module).Where("id = ?", identity).Select()
|
||||
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
|
||||
}
|
||||
return &module, err
|
||||
}
|
||||
|
||||
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 {
|
||||
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()
|
||||
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 0, 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 nil, err
|
||||
}
|
||||
return res, nil
|
||||
return res.RowsAffected(), err
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
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}
|
||||
}
|
||||
+33
-23
@@ -2,42 +2,52 @@ package model
|
||||
|
||||
import (
|
||||
"github.com/go-pg/pg"
|
||||
"github.com/go-pg/pg/orm"
|
||||
"github.com/integration-system/isp-lib/database"
|
||||
"isp-config-service/entity"
|
||||
)
|
||||
|
||||
type SchemaRepository struct {
|
||||
DB orm.DB
|
||||
type SchemaRepository interface {
|
||||
Snapshot() ([]entity.ConfigSchema, error)
|
||||
Upsert(schema entity.ConfigSchema) (*entity.ConfigSchema, error)
|
||||
Delete(identities []string) (int, error)
|
||||
}
|
||||
|
||||
func (r *SchemaRepository) InsertConfigSchema(s *entity.ConfigSchema) (*entity.ConfigSchema, error) {
|
||||
_, err := r.DB.Model(s).Returning("*").Insert()
|
||||
return s, err
|
||||
type schemaRepPg struct {
|
||||
rxClient *database.RxDbClient
|
||||
}
|
||||
|
||||
func (r *SchemaRepository) UpdateConfigSchema(s *entity.ConfigSchema) (*entity.ConfigSchema, error) {
|
||||
_, err := r.DB.Model(s).Returning("*").WherePK().Update()
|
||||
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) GetSchemasByModulesId(modulesId []int32) ([]entity.ConfigSchema, error) {
|
||||
var res []entity.ConfigSchema
|
||||
err := r.DB.Model(&res).Where("module_id IN (?)", pg.In(modulesId)).Select()
|
||||
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
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return res, nil
|
||||
return &schema, 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
|
||||
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
|
||||
}
|
||||
return res.RowsAffected(), err
|
||||
}
|
||||
@@ -1,134 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
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: "*"
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,134 +0,0 @@
|
||||
{
|
||||
"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."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,164 +0,0 @@
|
||||
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
@@ -0,0 +1,105 @@
|
||||
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()
|
||||
}
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
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 {
|
||||
CurrentLeaderAddress string
|
||||
IsLeader bool
|
||||
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.leaderObsCh)
|
||||
return r.r.Shutdown().Error()
|
||||
}
|
||||
|
||||
func (r *Raft) listenLeader() {
|
||||
defer close(r.changeLeaderCh)
|
||||
|
||||
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 != "",
|
||||
}:
|
||||
case <-r.closer:
|
||||
return
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
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
|
||||
}
|
||||
@@ -1,145 +0,0 @@
|
||||
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()
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
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())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
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{})
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
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 {
|
||||
bytes, err := json.Marshal(addressList)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
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 {
|
||||
bytes, err := json.Marshal(addressList)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
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),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
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
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
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 {
|
||||
bytes, err := json.Marshal(routes)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
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
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
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{},
|
||||
}
|
||||
}
|
||||
@@ -1,154 +0,0 @@
|
||||
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
@@ -1,262 +0,0 @@
|
||||
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)
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
package socket
|
||||
|
||||
func must(err error) {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
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())
|
||||
})
|
||||
}
|
||||
@@ -1,134 +0,0 @@
|
||||
{
|
||||
"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.
|
Before Width: | Height: | Size: 445 B |
Binary file not shown.
|
Before Width: | Height: | Size: 1.1 KiB |
@@ -1,95 +0,0 @@
|
||||
<!-- 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>
|
||||
@@ -1,67 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en-US">
|
||||
<body onload="run()">
|
||||
</body>
|
||||
</html>
|
||||
<script>
|
||||
'use strict';
|
||||
function run () {
|
||||
var oauth2 = window.opener.swaggerUIRedirectOauth2;
|
||||
var sentState = oauth2.state;
|
||||
var redirectUrl = oauth2.redirectUrl;
|
||||
var isValid, qp, arr;
|
||||
|
||||
if (/code|token|error/.test(window.location.hash)) {
|
||||
qp = window.location.hash.substring(1);
|
||||
} else {
|
||||
qp = location.search.substring(1);
|
||||
}
|
||||
|
||||
arr = qp.split("&")
|
||||
arr.forEach(function (v,i,_arr) { _arr[i] = '"' + v.replace('=', '":"') + '"';})
|
||||
qp = qp ? JSON.parse('{' + arr.join() + '}',
|
||||
function (key, value) {
|
||||
return key === "" ? value : decodeURIComponent(value)
|
||||
}
|
||||
) : {}
|
||||
|
||||
isValid = qp.state === sentState
|
||||
|
||||
if ((
|
||||
oauth2.auth.schema.get("flow") === "accessCode"||
|
||||
oauth2.auth.schema.get("flow") === "authorizationCode"
|
||||
) && !oauth2.auth.code) {
|
||||
if (!isValid) {
|
||||
oauth2.errCb({
|
||||
authId: oauth2.auth.name,
|
||||
source: "auth",
|
||||
level: "warning",
|
||||
message: "Authorization may be unsafe, passed state was changed in server Passed state wasn't returned from auth server"
|
||||
});
|
||||
}
|
||||
|
||||
if (qp.code) {
|
||||
delete oauth2.state;
|
||||
oauth2.auth.code = qp.code;
|
||||
oauth2.callback({auth: oauth2.auth, redirectUrl: redirectUrl});
|
||||
} else {
|
||||
let oauthErrorMsg
|
||||
if (qp.error) {
|
||||
oauthErrorMsg = "["+qp.error+"]: " +
|
||||
(qp.error_description ? qp.error_description+ ". " : "no accessCode received from the server. ") +
|
||||
(qp.error_uri ? "More info: "+qp.error_uri : "");
|
||||
}
|
||||
|
||||
oauth2.errCb({
|
||||
authId: oauth2.auth.name,
|
||||
source: "auth",
|
||||
level: "error",
|
||||
message: oauthErrorMsg || "[Authorization failed]: no accessCode received from the server"
|
||||
});
|
||||
}
|
||||
} else {
|
||||
oauth2.callback({auth: oauth2.auth, token: qp, isValid: isValid, redirectUrl: redirectUrl});
|
||||
}
|
||||
window.close();
|
||||
}
|
||||
</script>
|
||||
@@ -1,93 +0,0 @@
|
||||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.SwaggerUIBundle=t():e.SwaggerUIBundle=t()}(this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var i=n[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,t),i.l=!0,i.exports}var n={};return t.m=e,t.c=n,t.i=function(e){return e},t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="/dist",t(t.s=1229)}([function(e,t,n){"use strict";e.exports=n(92)},function(e,t,n){e.exports=n(1009)()},function(e,t,n){"use strict";t.__esModule=!0,t.default=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}},function(e,t,n){"use strict";t.__esModule=!0;var r=n(337),i=function(e){return e&&e.__esModule?e:{default:e}}(r);t.default=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),(0,i.default)(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}()},function(e,t,n){e.exports={default:n(605),__esModule:!0}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var i=n(579),o=r(i),a=n(336),s=r(a),u=n(48),l=r(u);t.default=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+(void 0===t?"undefined":(0,l.default)(t)));e.prototype=(0,s.default)(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(o.default?(0,o.default)(e,t):e.__proto__=t)}},function(e,t,n){"use strict";t.__esModule=!0;var r=n(48),i=function(e){return e&&e.__esModule?e:{default:e}}(r);t.default=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!==(void 0===t?"undefined":(0,i.default)(t))&&"function"!=typeof t?e:t}},function(e,t,n){!function(t,n){e.exports=n()}(0,function(){"use strict";function e(e,t){t&&(e.prototype=Object.create(t.prototype)),e.prototype.constructor=e}function t(e){return o(e)?e:O(e)}function n(e){return a(e)?e:M(e)}function r(e){return s(e)?e:T(e)}function i(e){return o(e)&&!u(e)?e:P(e)}function o(e){return!(!e||!e[ln])}function a(e){return!(!e||!e[cn])}function s(e){return!(!e||!e[pn])}function u(e){return a(e)||s(e)}function l(e){return!(!e||!e[fn])}function c(e){return e.value=!1,e}function p(e){e&&(e.value=!0)}function f(){}function h(e,t){t=t||0;for(var n=Math.max(0,e.length-t),r=new Array(n),i=0;i<n;i++)r[i]=e[i+t];return r}function d(e){return void 0===e.size&&(e.size=e.__iterate(v)),e.size}function m(e,t){if("number"!=typeof t){var n=t>>>0;if(""+n!==t||4294967295===n)return NaN;t=n}return t<0?d(e)+t:t}function v(){return!0}function g(e,t,n){return(0===e||void 0!==n&&e<=-n)&&(void 0===t||void 0!==n&&t>=n)}function y(e,t){return b(e,t,0)}function _(e,t){return b(e,t,t)}function b(e,t,n){return void 0===e?n:e<0?Math.max(0,t+e):void 0===t?e:Math.min(t,e)}function x(e){this.next=e}function w(e,t,n,r){var i=0===e?t:1===e?n:[t,n];return r?r.value=i:r={value:i,done:!1},r}function k(){return{value:void 0,done:!0}}function E(e){return!!A(e)}function S(e){return e&&"function"==typeof e.next}function C(e){var t=A(e);return t&&t.call(e)}function A(e){var t=e&&(wn&&e[wn]||e[kn]);if("function"==typeof t)return t}function D(e){return e&&"number"==typeof e.length}function O(e){return null===e||void 0===e?B():o(e)?e.toSeq():z(e)}function M(e){return null===e||void 0===e?B().toKeyedSeq():o(e)?a(e)?e.toSeq():e.fromEntrySeq():L(e)}function T(e){return null===e||void 0===e?B():o(e)?a(e)?e.entrySeq():e.toIndexedSeq():q(e)}function P(e){return(null===e||void 0===e?B():o(e)?a(e)?e.entrySeq():e:q(e)).toSetSeq()}function I(e){this._array=e,this.size=e.length}function R(e){var t=Object.keys(e);this._object=e,this._keys=t,this.size=t.length}function j(e){this._iterable=e,this.size=e.length||e.size}function N(e){this._iterator=e,this._iteratorCache=[]}function F(e){return!(!e||!e[Sn])}function B(){return Cn||(Cn=new I([]))}function L(e){var t=Array.isArray(e)?new I(e).fromEntrySeq():S(e)?new N(e).fromEntrySeq():E(e)?new j(e).fromEntrySeq():"object"==typeof e?new R(e):void 0;if(!t)throw new TypeError("Expected Array or iterable object of [k, v] entries, or keyed object: "+e);return t}function q(e){var t=U(e);if(!t)throw new TypeError("Expected Array or iterable object of values: "+e);return t}function z(e){var t=U(e)||"object"==typeof e&&new R(e);if(!t)throw new TypeError("Expected Array or iterable object of values, or keyed object: "+e);return t}function U(e){return D(e)?new I(e):S(e)?new N(e):E(e)?new j(e):void 0}function W(e,t,n,r){var i=e._cache;if(i){for(var o=i.lengthLine truncated
|
||||
object-assign
|
||||
(c) Sindre Sorhus
|
||||
@license MIT
|
||||
*/
|
||||
var i=Object.getOwnPropertySymbols,o=Object.prototype.hasOwnProperty,a=Object.prototype.propertyIsEnumerable;e.exports=function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},n=0;n<10;n++)t["_"+String.fromCharCode(n)]=n;if("0123456789"!==Object.getOwnPropertyNames(t).map(function(e){return t[e]}).join(""))return!1;var r={};return"abcdefghijklmnopqrst".split("").forEach(function(e){r[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},r)).join("")}catch(e){return!1}}()?Object.assign:function(e,t){for(var n,s,u=r(e),l=1;l<arguments.length;l++){n=Object(arguments[l]);for(var c in n)o.call(n,c)&&(u[c]=n[c]);if(i){s=i(n);for(var p=0;p<s.length;p++)a.call(n,s[p])&&(u[s[p]]=n[s[p]])}}return u}},function(e,t,n){"use strict";function r(e,t){return 1===e.nodeType&&e.getAttribute(d)===String(t)||8===e.nodeType&&e.nodeValue===" react-text: "+t+" "||8===e.nodeType&&e.nodeValue===" react-empty: "+t+" "}function i(e){for(var t;t=e._renderedComponent;)e=t;return e}function o(e,t){var n=i(e);n._hostNode=t,t[v]=n}function a(e){var t=e._hostNode;t&&(delete t[v],e._hostNode=null)}function s(e,t){if(!(e._flags&m.hasCachedChildNodes)){var n=e._renderedChildren,a=t.firstChild;e:for(var s in n)if(n.hasOwnProperty(s)){var u=n[s],l=i(u)._domID;if(0!==l){for(;null!==a;a=a.nextSibling)if(r(a,l)){o(u,a);continue e}p("32",l)}}e._flags|=m.hasCachedChildNodes}}function u(e){if(e[v])return e[v];for(var t=[];!e[v];){if(t.push(e),!e.parentNode)return null;e=e.parentNode}for(var n,r;e&&(r=e[v]);e=t.pop())n=r,t.length&&s(r,e);return n}function l(e){var t=u(e);return null!=t&&t._hostNode===e?t:null}function c(e){if(void 0===e._hostNode&&p("33"),e._hostNode)return e._hostNode;for(var t=[];!e._hostNode;)t.push(e),e._hostParent||p("34"),e=e._hostParent;for(;t.length;e=t.pop())s(e,e._hostNode);return e._hostNode}var p=n(11),f=n(89),h=n(466),d=(n(8),f.ID_ATTRIBUTE_NAME),m=h,v="__reactInternalInstance$"+Math.random().toString(36).slice(2),g={getClosestInstanceFromNode:u,getInstanceFromNode:l,getNodeFromInstance:c,precacheChildNodes:s,precacheNode:o,uncacheNode:a};e.exports=g},function(e,t){var n=e.exports={version:"2.5.4"};"number"==typeof __e&&(__e=n)},function(e,t){var n;n=function(){return this}();try{n=n||Function("return this")()||(0,eval)("this")}catch(e){"object"==typeof window&&(n=window)}e.exports=n},function(e,t,n){"use strict";function r(e){var t={};return null!==e&&Object.keys(e).forEach(function(n){e[n].forEach(function(e){t[String(e)]=n})}),t}function i(e,t){if(t=t||{},Object.keys(t).forEach(function(t){if(-1===a.indexOf(t))throw new o('Unknown option "'+t+'" is met in definition of "'+e+'" YAML type.')}),this.tag=e,this.kind=t.kind||null,this.resolve=t.resolve||function(){return!0},this.construct=t.construct||function(e){return e},this.instanceOf=t.instanceOf||null,this.predicate=t.predicate||null,this.represent=t.represent||null,this.defaultStyle=t.defaultStyle||null,this.styleAliases=r(t.styleAliases||null),-1===s.indexOf(this.kind))throw new o('Unknown kind "'+this.kind+'" is specified for "'+e+'" YAML type.')}var o=n(116),a=["kind","resolve","construct","instanceOf","predicate","represent","defaultStyle","styleAliases"],s=["scalar","sequence","mapping"];e.exports=i},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var i=n(578),o=r(i),a=n(96),s=r(a);t.default=function(){function e(e,t){var n=[],r=!0,i=!1,o=void 0;try{for(var a,u=(0,s.default)(e);!(r=(a=u.next()).done)&&(n.push(a.value),!t||n.length!==t);r=!0);}catch(e){i=!0,o=e}finally{try{!r&&u.return&&u.return()}finally{if(i)throw o}}return n}return function(t,n){if(Array.isArray(t))return t;if((0,o.default)(Object(t)))return e(t,n);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}()},function(e,t,n){var r=n(368)("wks"),i=n(205),o=n(32).Symbol,a="function"==typeof o;(e.exports=function(e){return r[e]||(r[e]=a&&o[e]||(a?o:i)("Symbol."+e))}).store=r},function(e,t,n){"use strict";t.__esModule=!0;var r=n(27),i=function(e){return e&&e.__esModule?e:{default:e}}(r);t.default=i.default||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}},function(e,t,n){var r=n(191)("wks"),i=n(133),o=n(24).Symbol,a="function"==typeof o;(e.exports=function(e){return r[e]||(r[e]=a&&o[e]||(a?o:i)("Symbol."+e))}).store=r},function(e,t){var n=Array.isArray;e.exports=n},function(e,t,n){var r=n(24),i=n(15),o=n(54),a=n(57),s=n(56),u=function(e,t,n){var l,c,p,f=e&u.F,h=e&u.G,d=e&u.S,m=e&u.P,v=e&u.B,g=e&u.W,y=h?i:i[t]||(i[t]={}),_=y.prototype,b=h?r:d?r[t]:(r[t]||{}).prototype;h&&(n=t);for(l in n)(c=!f&&b&&void 0!==b[l])&&s(y,l)||(p=c?b[l]:n[l],y[l]=h&&"function"!=typeof b[l]?n[l]:v&&c?o(p,r):g&&b[l]==p?function(e){var t=function(t,n,r){if(this instanceof e){switch(arguments.length){case 0:return new e;case 1:return new e(t);case 2:return new e(t,n)}returnLine truncated
|
||||
* The buffer module from node.js, for the browser.
|
||||
*
|
||||
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
|
||||
* @license MIT
|
||||
*/
|
||||
var Y=n(583),$=n(779),Z=n(396);t.Buffer=o,t.SlowBuffer=m,t.INSPECT_MAX_BYTES=50,o.TYPED_ARRAY_SUPPORT=void 0!==e.TYPED_ARRAY_SUPPORT?e.TYPED_ARRAY_SUPPORT:function(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()&&"function"==typeof e.subarray&&0===e.subarray(1,1).byteLength}catch(e){return!1}}(),t.kMaxLength=r(),o.poolSize=8192,o._augment=function(e){return e.__proto__=o.prototype,e},o.from=function(e,t,n){return a(null,e,t,n)},o.TYPED_ARRAY_SUPPORT&&(o.prototype.__proto__=Uint8Array.prototype,o.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&o[Symbol.species]===o&&Object.defineProperty(o,Symbol.species,{value:null,configurable:!0})),o.alloc=function(e,t,n){return u(null,e,t,n)},o.allocUnsafe=function(e){return l(null,e)},o.allocUnsafeSlow=function(e){return l(null,e)},o.isBuffer=function(e){return!(null==e||!e._isBuffer)},o.compare=function(e,t){if(!o.isBuffer(e)||!o.isBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var n=e.length,r=t.length,i=0,a=Math.min(n,r);i<a;++i)if(e[i]!==t[i]){n=e[i],r=t[i];break}return n<r?-1:r<n?1:0},o.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},o.concat=function(e,t){if(!Z(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return o.alloc(0);var n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var r=o.allocUnsafe(t),i=0;for(n=0;n<e.length;++n){var a=e[n];if(!o.isBuffer(a))throw new TypeError('"list" argument must be an Array of Buffers');a.copy(r,i),i+=a.length}return r},o.byteLength=v,o.prototype._isBuffer=!0,o.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)y(this,t,t+1);return this},o.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)y(this,t,t+3),y(this,t+1,t+2);return this},o.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)y(this,t,t+7),y(this,t+1,t+6),y(this,t+2,t+5),y(this,t+3,t+4);return this},o.prototype.toString=function(){var e=0|this.length;return 0===e?"":0===arguments.length?D(this,0,e):g.apply(this,arguments)},o.prototype.equals=function(e){if(!o.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===o.compare(this,e)},o.prototype.inspect=function(){var e="",n=t.INSPECT_MAX_BYTES;return this.length>0&&(e=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(e+=" ... ")),"<Buffer "+e+">"},o.prototype.compare=function(e,t,n,r,i){if(!o.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===i&&(i=this.length),t<0||n>e.length||r<0||i>this.length)throw new RangeError("out of range index");if(r>=i&&t>=n)return 0;if(r>=i)return-1;if(t>=n)return 1;if(t>>>=0,n>>>=0,r>>>=0,i>>>=0,this===e)return 0;for(var a=i-r,s=n-t,u=Math.min(a,s),l=this.slice(r,i),c=e.slice(t,n),p=0;p<u;++p)if(l[p]!==c[p]){a=l[p],s=c[p];break}return a<s?-1:s<a?1:0},o.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},o.prototype.indexOf=function(e,t,n){return _(this,e,t,n,!0)},o.prototype.lastIndexOf=function(e,t,n){return _(this,e,t,n,!1)},o.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t|=0,isFinite(n)?(n|=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}var i=this.length-t;if((void 0===n||n>i)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var o=!1;;)switch(r){case"hex":return x(this,e,t,n);case"utf8":case"utf-8":return w(this,e,t,n);case"ascii":return k(this,e,t,n);case"latin1":case"binary":return E(this,e,t,n);case"base64":return S(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,e,t,n);default:if(o)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),o=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Q=4096;o.prototype.slice=function(e,t){var n=this.length;e=~~e,t=void 0===t?n:~~t,e<0?(e+=n)<0&&(e=0):e>n&&(e=n),t<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e);var r;if(o.TYPED_ARRAY_SUPPORT)r=this.subarray(e,t),r.__proto__=o.prototype;else{var i=t-e;r=new o(i,void 0);for(var a=0;a<i;++a)r[a]=this[a+e]}return r},o.prototype.readUIntLE=function(e,t,n){e|=0,t|=0,n||R(e,t,this.length);for(var r=this[e],i=1,o=0;++o<t&&(i*=256);)r+=this[e+o]*i;return r},o.prototype.readUIntBE=function(e,t,n){Line truncated
|
||||
* @description Recursive object extending
|
||||
* @author Viacheslav Lotsmanov <lotsmanov89@gmail.com>
|
||||
* @license MIT
|
||||
*
|
||||
* The MIT License (MIT)
|
||||
*
|
||||
* Copyright (c) 2013-2015 Viacheslav Lotsmanov
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
function n(e){return e instanceof t||e instanceof Date||e instanceof RegExp}function r(e){if(e instanceof t){var n=new t(e.length);return e.copy(n),n}if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp)return new RegExp(e);throw new Error("Unexpected situation")}function i(e){var t=[];return e.forEach(function(e,a){"object"==typeof e&&null!==e?Array.isArray(e)?t[a]=i(e):n(e)?t[a]=r(e):t[a]=o({},e):t[a]=e}),t}var o=e.exports=function(){if(arguments.length<1||"object"!=typeof arguments[0])return!1;if(arguments.length<2)return arguments[0];var e,t,a=arguments[0],s=Array.prototype.slice.call(arguments,1);return s.forEach(function(s){"object"!=typeof s||Array.isArray(s)||Object.keys(s).forEach(function(u){return t=a[u],e=s[u],e===a?void 0:"object"!=typeof e||null===e?void(a[u]=e):Array.isArray(e)?void(a[u]=i(e)):n(e)?void(a[u]=r(e)):"object"!=typeof t||null===t||Array.isArray(t)?void(a[u]=o({},e)):void(a[u]=o(t,e))})}),a}}).call(t,n(43).Buffer)},function(e,t){e.exports={Aacute:"Á",aacute:"á",Abreve:"Ă",abreve:"ă",ac:"∾",acd:"∿",acE:"∾̳",Acirc:"Â",acirc:"â",acute:"´",Acy:"А",acy:"а",AElig:"Æ",aelig:"æ",af:"",Afr:"𝔄",afr:"𝔞",Agrave:"À",agrave:"à",alefsym:"ℵ",aleph:"ℵ",Alpha:"Α",alpha:"α",Amacr:"Ā",amacr:"ā",amalg:"⨿",amp:"&",AMP:"&",andand:"⩕",And:"⩓",and:"∧",andd:"⩜",andslope:"⩘",andv:"⩚",ang:"∠",ange:"⦤",angle:"∠",angmsdaa:"⦨",angmsdab:"⦩",angmsdac:"⦪",angmsdad:"⦫",angmsdae:"⦬",angmsdaf:"⦭",angmsdag:"⦮",angmsdah:"⦯",angmsd:"∡",angrt:"∟",angrtvb:"⊾",angrtvbd:"⦝",angsph:"∢",angst:"Å",angzarr:"⍼",Aogon:"Ą",aogon:"ą",Aopf:"𝔸",aopf:"𝕒",apacir:"⩯",ap:"≈",apE:"⩰",ape:"≊",apid:"≋",apos:"'",ApplyFunction:"",approx:"≈",approxeq:"≊",Aring:"Å",aring:"å",Ascr:"𝒜",ascr:"𝒶",Assign:"≔",ast:"*",asymp:"≈",asympeq:"≍",Atilde:"Ã",atilde:"ã",Auml:"Ä",auml:"ä",awconint:"∳",awint:"⨑",backcong:"≌",backepsilon:"϶",backprime:"‵",backsim:"∽",backsimeq:"⋍",Backslash:"∖",Barv:"⫧",barvee:"⊽",barwed:"⌅",Barwed:"⌆",barwedge:"⌅",bbrk:"⎵",bbrktbrk:"⎶",bcong:"≌",Bcy:"Б",bcy:"б",bdquo:"„",becaus:"∵",because:"∵",Because:"∵",bemptyv:"⦰",bepsi:"϶",bernou:"ℬ",Bernoullis:"ℬ",Beta:"Β",beta:"β",beth:"ℶ",between:"≬",Bfr:"𝔅",bfr:"𝔟",bigcap:"⋂",bigcirc:"◯",bigcup:"⋃",bigodot:"⨀",bigoplus:"⨁",bigotimes:"⨂",bigsqcup:"⨆",bigstar:"★",bigtriangledown:"▽",bigtriangleup:"△",biguplus:"⨄",bigvee:"⋁",bigwedge:"⋀",bkarow:"⤍",blacklozenge:"⧫",blacksquare:"▪",blacktriangle:"▴",blacktriangledown:"▾",blacktriangleleft:"◂",blacktriangleright:"▸",blank:"␣",blk12:"▒",blk14:"░",blk34:"▓",block:"█",bne:"=⃥",bnequiv:"≡⃥",bNot:"⫭",bnot:"⌐",Bopf:"𝔹",bopf:"𝕓",bot:"⊥",bottom:"⊥",bowtie:"⋈",boxbox:"⧉",boxdl:"┐",boxdL:"╕",boxDl:"╖",boxDL:"╗",boxdr:"┌",boxdR:"╒",boxDr:"╓",boxDR:"╔",boxh:"─",boxH:"═",boxhd:"┬",boxHd:"╤",boxhD:"╥",boxHD:"╦",boxhu:"┴",boxHu:"╧",boxhU:"╨",boxHU:"╩",boxminus:"⊟",boxplus:"⊞",boxtimes:"⊠",boxul:"┘",boxuL:"╛",boxUl:"╜",boxUL:"╝",boxur:"└",boxuR:"╘",boxUr:"╙",boxUR:"╚",boxv:"│",boxV:"║",boxvh:"┼",boxvH:"╪",boxVh:"╫",boxVH:"╬",boxvl:"┤",boxvL:"╡",boxVl:"╢",boxVL:"╣",boxvr:"├",boxvR:"╞",boxVr:"╟",boxVR:"╠",bprime:"‵",breve:"˘",Breve:"˘",brvbar:"¦",bscr:"𝒷",Bscr:"ℬ",bsemi:"⁏",bsim:"∽",bsime:"⋍",bsolb:"⧅",bsol:"\\",bsolhsub:"⟈",bull:"•",bullet:"•",bump:"≎",bumpE:"⪮",bumpe:"≏",Bumpeq:"≎",bumpeq:"≏",Cacute:"Ć",cacute:"ć",capand:"⩄",capbrcup:"⩉",capcap:"⩋",cap:"∩",Cap:"⋒",capcup:"⩇",capdot:"⩀",CapitalDifferentialD:"ⅅ",caps:"∩︀",caret:"⁁",caron:"ˇ",Cayleys:"ℭ",ccaps:"⩍",Ccaron:"Č",ccaron:"č",Ccedil:"Ç",ccedil:"ç",Ccirc:"Ĉ",ccirc:"ĉ",Cconint:"∰",ccups:"⩌",ccupssm:"⩐",Cdot:"Ċ",cdot:"ċ",cedil:"¸",Cedilla:"¸",cemptyv:"⦲",cent:"¢",centerdot:"·",CenterDot:"·",cfr:"𝔠",Cfr:"ℭ",CHcy:"Ч",chcy:"ч",check:"✓",checkmark:"✓",Chi:"Χ",chi:"χ",circ:"ˆ",circeq:"≗",circlearrowleft:"↺",circlearrowright:"↻",circledast:"⊛",circledcirc:"⊚",circleddash:"⊝",CircleDot:"⊙",circledR:"®",circledS:"Ⓢ",CircleMinus:"⊖",CirclePlus:"⊕",CircleTimes:"⊗",cir:"○",cirE:"⧃",cire:"≗",cirfnint:"⨐",cirmid:"⫯",cirscir:"⧂",ClockwiseContourIntegral:"∲",CloseCurlyDoubleQuote:"”",CloseCurlyQuote:"’",clubs:"♣",clubsuit:"♣",colon:":",Colon:"∷",Colone:"⩴",colone:"≔",coloneq:"≔",comma:",",commat:"@",comp:"∁",compfn:"∘",complement:"∁",complexes:"ℂ",cong:"≅",congdot:"⩭",Congruent:"≡",conint:"∮",Conint:"∯",ContourIntegral:"∮",copf:"𝕔",Copf:"ℂ",coprod:"∐",Coproduct:"∐",copy:"©",COPY:"©",copysr:"℗",CounterClockwiseContourIntegral:"∳",crarr:"↵",cross:"✗",Cross:"⨯",Cscr:"𝒞",cscr:"𝒸",csub:"⫏",csube:"⫑",csup:"⫐",csupe:"⫒",ctdot:"⋯",cudarrl:"⤸",cudarrr:"⤵",cLine truncated
|
||||
* Checks if an event is supported in the current execution environment.
|
||||
*
|
||||
* NOTE: This will not work correctly for non-generic events such as `change`,
|
||||
* `reset`, `load`, `error`, and `select`.
|
||||
*
|
||||
* Borrows from Modernizr.
|
||||
*
|
||||
* @param {string} eventNameSuffix Event name, e.g. "click".
|
||||
* @param {?boolean} capture Check if the capture phase is supported.
|
||||
* @return {boolean} True if the event is supported.
|
||||
* @internal
|
||||
* @license Modernizr 3.0.0pre (Custom Build) | MIT
|
||||
*/
|
||||
function r(e,t){if(!o.canUseDOM||t&&!("addEventListener"in document))return!1;var n="on"+e,r=n in document;if(!r){var a=document.createElement("div");a.setAttribute(n,"return;"),r="function"==typeof a[n]}return!r&&i&&"wheel"===e&&(r=document.implementation.hasFeature("Events.wheel","3.0")),r}var i,o=n(25);o.canUseDOM&&(i=document.implementation&&document.implementation.hasFeature&&!0!==document.implementation.hasFeature("","")),e.exports=r},function(e,t,n){"use strict";function r(e,t){var n=null===e||!1===e,r=null===t||!1===t;if(n||r)return n===r;var i=typeof e,o=typeof t;return"string"===i||"number"===i?"string"===o||"number"===o:"object"===o&&e.type===t.type&&e.key===t.key}e.exports=r},function(e,t,n){"use strict";var r=(n(13),n(33)),i=(n(10),r);e.exports=i},function(e,t,n){"use strict";function r(e){switch(e._type){case"Document":case"BlockQuote":case"List":case"Item":case"Paragraph":case"Heading":case"Emph":case"Strong":case"Link":case"Image":case"CustomInline":case"CustomBlock":return!0;default:return!1}}var i=function(e,t){this.current=e,this.entering=!0===t},o=function(){var e=this.current,t=this.entering;if(null===e)return null;var n=r(e);return t&&n?e._firstChild?(this.current=e._firstChild,this.entering=!0):this.entering=!1:e===this.root?this.current=null:null===e._next?(this.current=e._parent,this.entering=!1):(this.current=e._next,this.entering=!0),{entering:t,node:e}},a=function(e){return{current:e,root:e,entering:!0,next:o,resumeAt:i}},s=function(e,t){this._type=e,this._parent=null,this._firstChild=null,this._lastChild=null,this._prev=null,this._next=null,this._sourcepos=t,this._lastLineBlank=!1,this._open=!0,this._string_content=null,this._literal=null,this._listData={},this._info=null,this._destination=null,this._title=null,this._isFenced=!1,this._fenceChar=null,this._fenceLength=0,this._fenceOffset=null,this._level=null,this._onEnter=null,this._onExit=null},u=s.prototype;Object.defineProperty(u,"isContainer",{get:function(){return r(this)}}),Object.defineProperty(u,"type",{get:function(){return this._type}}),Object.defineProperty(u,"firstChild",{get:function(){return this._firstChild}}),Object.defineProperty(u,"lastChild",{get:function(){return this._lastChild}}),Object.defineProperty(u,"next",{get:function(){return this._next}}),Object.defineProperty(u,"prev",{get:function(){return this._prev}}),Object.defineProperty(u,"parent",{get:function(){return this._parent}}),Object.defineProperty(u,"sourcepos",{get:function(){return this._sourcepos}}),Object.defineProperty(u,"literal",{get:function(){return this._literal},set:function(e){this._literal=e}}),Object.defineProperty(u,"destination",{get:function(){return this._destination},set:function(e){this._destination=e}}),Object.defineProperty(u,"title",{get:function(){return this._title},set:function(e){this._title=e}}),Object.defineProperty(u,"info",{get:function(){return this._info},set:function(e){this._info=e}}),Object.defineProperty(u,"level",{get:function(){return this._level},set:function(e){this._level=e}}),Object.defineProperty(u,"listType",{get:function(){return this._listData.type},set:function(e){this._listData.type=e}}),Object.defineProperty(u,"listTight",{get:function(){return this._listData.tight},set:function(e){this._listData.tight=e}}),Object.defineProperty(u,"listStart",{get:function(){return this._listData.start},set:function(e){this._listData.start=e}}),Object.defineProperty(u,"listDelimiter",{get:function(){return this._listData.delimiter},set:function(e){this._listData.delimiter=e}}),Object.defineProperty(u,"onEnter",{get:function(){return this._onEnter},set:function(e){this._onEnter=e}}),Object.defineProperty(u,"onExit",{get:function(){return this._onExit},set:function(e){this._onExit=e}}),s.prototype.appendChild=function(e){e.unlink(),e._parent=this,this._lastChild?(this._lastChild._next=e,e._prev=this._lastChild,this._lastChild=e):(this._firstChild=e,this._lastChild=e)},s.prototype.prependChild=function(e){e.unlink(),e._parent=this,this._firstChild?(this._firstChild._prev=e,e._next=this._firstChild,this._firstChild=e):(this._firstChild=e,this._lastChild=e)},s.prototype.unlink=function(){this._prev?this._prev._next=this._next:this._parent&&(this._parent._firstChild=this._next),this._next?this._next._prev=this._prev:this._parent&&(this._parent._lastChild=this._prev),this._parent=null,this._next=null,this._prev=null},s.prototype.insertAfter=function(e){e.unlink(),e._next=this._next,e._next&&(e._next._prev=e),e._prev=this,this._next=e,e._parent=this._parent,e._next||(e._parent._lastChild=e)},s.prototype.insertBefore=function(e){e.unlink(),e._prev=this._prev,e._prev&&(e._prev._next=e),e._next=this,this._prev=e,e._parent=this._parent,e._prev||(e._parent._firstChild=e)},s.prototype.walker=function(){return new a(this)},e.exports=s},function(e,t,n){"use strict";function r(e){var t={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=0);return t}t.__esModule=!0,t.default=r,e.exports=t.default},function(e,t,n){"use
Line truncated
|
||||
String.prototype.repeat||function(){"use strict";var e=function(){try{var e={},t=Object.defineProperty,n=t(e,e,e)&&t}catch(e){}return n}(),t=function(e){if(null==this)throw TypeError();var t=String(this),n=e?Number(e):0;if(n!=n&&(n=0),n<0||n==1/0)throw RangeError();for(var r="";n;)n%2==1&&(r+=t),n>1&&(t+=t),n>>=1;return r};e?e(String.prototype,"repeat",{value:t,configurable:!0,writable:!0}):String.prototype.repeat=t}()},function(e,t,n){e.exports=function(e){function t(r){if(n[r])return n[r].exports;var i=n[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,t),i.l=!0,i.exports}var n={};return t.m=e,t.c=n,t.i=function(e){return e},t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=61)}([function(e,t){e.exports=n(42)},function(e,t){e.exports=n(27)},function(e,t){e.exports=n(48)},function(e,t){e.exports=n(20)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e){var t=e.openapi;return!!t&&(0,b.default)(t,"3")}function o(e){var t=e.swagger;return!!t&&(0,b.default)(t,"2")}function a(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";return e&&"object"===(void 0===e?"undefined":(0,v.default)(e))?(e.operationId||"").replace(/\s/g,"").length?w(e.operationId):s(t,n):null}function s(e,t){return""+x(t)+w(e)}function u(e,t){return x(t)+"-"+e}function l(e,t){return e&&e.paths?c(e,function(e){var n=e.pathName,r=e.method,i=e.operation;if(!i||"object"!==(void 0===i?"undefined":(0,v.default)(i)))return!1;var o=i.operationId;return[a(i,n,r),u(n,r),o].some(function(e){return e&&e===t})}):null}function c(e,t){return p(e,t,!0)||null}function p(e,t,n){if(!e||"object"!==(void 0===e?"undefined":(0,v.default)(e))||!e.paths||"object"!==(0,v.default)(e.paths))return null;var r=e.paths;for(var i in r)for(var o in r[i])if("PARAMETERS"!==o.toUpperCase()){var a=r[i][o];if(a&&"object"===(void 0===a?"undefined":(0,v.default)(a))){var s={spec:e,pathName:i,method:o.toUpperCase(),operation:a},u=t(s);if(n&&u)return s}}}function f(e){var t=e.spec,n=t.paths,r={};if(!n)return e;for(var i in n){var o=n[i];if((0,y.default)(o)){var s=o.parameters;for(var u in o)!function(e){var n=o[e];if(!(0,y.default)(n))return"continue";var u=a(n,i,e);if(u){r[u]?r[u].push(n):r[u]=[n];var l=r[u];if(l.length>1)l.forEach(function(e,t){e.__originalOperationId=e.__originalOperationId||e.operationId,e.operationId=""+u+(t+1)});else if(void 0!==n.operationId){var c=l[0];c.__originalOperationId=c.__originalOperationId||n.operationId,c.operationId=u}}if("parameters"!==e){var p=[],f={};for(var h in t)"produces"!==h&&"consumes"!==h&&"security"!==h||(f[h]=t[h],p.push(f));if(s&&(f.parameters=s,p.push(f)),p.length){var m=!0,v=!1,g=void 0;try{for(var _,b=(0,d.default)(p);!(m=(_=b.next()).done);m=!0){var x=_.value;for(var w in x)if(n[w]){if("parameters"===w){var k=!0,E=!1,S=void 0;try{for(var C,A=(0,d.default)(x[w]);!(k=(C=A.next()).done);k=!0)!function(){var e=C.value;n[w].some(function(t){return t.name===e.name})||n[w].push(e)}()}catch(e){E=!0,S=e}finally{try{!k&&A.return&&A.return()}finally{if(E)throw S}}}}else n[w]=x[w]}}catch(e){v=!0,g=e}finally{try{!m&&b.return&&b.return()}finally{if(v)throw g}}}}}(u)}}return e}Object.defineProperty(t,"__esModule",{value:!0});var h=n(16),d=r(h),m=n(2),v=r(m);t.isOAS3=i,t.isSwagger2=o,t.opId=a,t.idFromPathMethod=s,t.legacyIdFromPathMethod=u,t.getOperationRaw=l,t.findOperation=c,t.eachOperation=p,t.normalizeSwagger=f;var g=n(54),y=r(g),_=n(21),b=r(_),x=function(e){return String.prototype.toLowerCase.call(e)},w=function(e){return e.replace(/[^\w]/gi,"_")}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return"object"===(void 0===e?"undefined":(0,b.default)(e))&&(t=e,e=t.url),t.headers=t.headers||{},A.mergeInQueryOrForm(t),t.requestInterceptor&&(t=t.requestInterceptor(t)||t),/multipart\/form-data/i.test(t.headers["content-type"]||t.headers["Content-Type"])&&(delete t.headers["content-type"],delete t.headers["Content-Type"]),(t.userFetch||fetch)(t.url,t).then(function(n){var r=A.serializeRes(n,e,t).then(function(e){return t.responseInterceptor&&(e=t.responseInterceptor(e)||e),e});if(!n.ok){var i=new Error(n.statusText);return i.statusCode=i.status=n.status,r.then(function(e){throw i.response=e,i},function(e){throw i.responseError=e,i})}return r})}function o(e,t){return"application/json"===t?JSON.parse(e):E.default.safeLoad(e)}function a(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=n.loadSpec,i=void 0!==r&&r,a={ok:e.ok,url:e.url||t,status:e.status,statusText:e.statusText,headers:s(e.headers)},u=a.headers["content-type"],l=i||D(u);return(l?e.text:e.blob||e.buffer).call(e).then(function(e){if(a.text=e,a.data=e,lLine truncated
|
||||
* Autolinker.js
|
||||
* 0.15.3
|
||||
*
|
||||
* Copyright(c) 2015 Gregory Jacobs <greg@greg-jacobs.com>
|
||||
* MIT Licensed. http://www.opensource.org/licenses/mit-license.php
|
||||
*
|
||||
* https://github.com/gregjacobs/Autolinker.js
|
||||
*/
|
||||
var e=function(t){e.Util.assign(this,t)};return e.prototype={constructor:e,urls:!0,email:!0,twitter:!0,newWindow:!0,stripPrefix:!0,truncate:void 0,className:"",htmlParser:void 0,matchParser:void 0,tagBuilder:void 0,link:function(e){for(var t=this.getHtmlParser(),n=t.parse(e),r=0,i=[],o=0,a=n.length;o<a;o++){var s=n[o],u=s.getType(),l=s.getText();if("element"===u)"a"===s.getTagName()&&(s.isClosing()?r=Math.max(r-1,0):r++),i.push(l);else if("entity"===u)i.push(l);else if(0===r){var c=this.linkifyStr(l);i.push(c)}else i.push(l)}return i.join("")},linkifyStr:function(e){return this.getMatchParser().replace(e,this.createMatchReturnVal,this)},createMatchReturnVal:function(t){var n;return this.replaceFn&&(n=this.replaceFn.call(this,this,t)),"string"==typeof n?n:!1===n?t.getMatchedText():n instanceof e.HtmlTag?n.toString():this.getTagBuilder().build(t).toString()},getHtmlParser:function(){var t=this.htmlParser;return t||(t=this.htmlParser=new e.htmlParser.HtmlParser),t},getMatchParser:function(){var t=this.matchParser;return t||(t=this.matchParser=new e.matchParser.MatchParser({urls:this.urls,email:this.email,twitter:this.twitter,stripPrefix:this.stripPrefix})),t},getTagBuilder:function(){var t=this.tagBuilder;return t||(t=this.tagBuilder=new e.AnchorTagBuilder({newWindow:this.newWindow,truncate:this.truncate,className:this.className})),t}},e.link=function(t,n){return new e(n).link(t)},e.match={},e.htmlParser={},e.matchParser={},e.Util={abstractMethod:function(){throw"abstract"},assign:function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e},extend:function(t,n){var r=t.prototype,i=function(){};i.prototype=r;var o;o=n.hasOwnProperty("constructor")?n.constructor:function(){r.constructor.apply(this,arguments)};var a=o.prototype=new i;return a.constructor=o,a.superclass=r,delete n.constructor,e.Util.assign(a,n),o},ellipsis:function(e,t,n){return e.length>t&&(n=null==n?"..":n,e=e.substring(0,t-n.length)+n),e},indexOf:function(e,t){if(Array.prototype.indexOf)return e.indexOf(t);for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1},splitAndCapture:function(e,t){if(!t.global)throw new Error("`splitRegex` must have the 'g' flag set");for(var n,r=[],i=0;n=t.exec(e);)r.push(e.substring(i,n.index)),r.push(n[0]),i=n.index+n[0].length;return r.push(e.substring(i)),r}},e.HtmlTag=e.Util.extend(Object,{whitespaceRegex:/\s+/,constructor:function(t){e.Util.assign(this,t),this.innerHtml=this.innerHtml||this.innerHTML},setTagName:function(e){return this.tagName=e,this},getTagName:function(){return this.tagName||""},setAttr:function(e,t){return this.getAttrs()[e]=t,this},getAttr:function(e){return this.getAttrs()[e]},setAttrs:function(t){var n=this.getAttrs();return e.Util.assign(n,t),this},getAttrs:function(){return this.attrs||(this.attrs={})},setClass:function(e){return this.setAttr("class",e)},addClass:function(t){for(var n,r=this.getClass(),i=this.whitespaceRegex,o=e.Util.indexOf,a=r?r.split(i):[],s=t.split(i);n=s.shift();)-1===o(a,n)&&a.push(n);return this.getAttrs().class=a.join(" "),this},removeClass:function(t){for(var n,r=this.getClass(),i=this.whitespaceRegex,o=e.Util.indexOf,a=r?r.split(i):[],s=t.split(i);a.length&&(n=s.shift());){var u=o(a,n);-1!==u&&a.splice(u,1)}return this.getAttrs().class=a.join(" "),this},getClass:function(){return this.getAttrs().class||""},hasClass:function(e){return-1!==(" "+this.getClass()+" ").indexOf(" "+e+" ")},setInnerHtml:function(e){return this.innerHtml=e,this},getInnerHtml:function(){return this.innerHtml||""},toString:function(){var e=this.getTagName(),t=this.buildAttrsStr();return t=t?" "+t:"",["<",e,t,">",this.getInnerHtml(),"</",e,">"].join("")},buildAttrsStr:function(){if(!this.attrs)return"";var e=this.getAttrs(),t=[];for(var n in e)e.hasOwnProperty(n)&&t.push(n+'="'+e[n]+'"');return t.join(" ")}}),e.AnchorTagBuilder=e.Util.extend(Object,{constructor:function(t){e.Util.assign(this,t)},build:function(t){return new e.HtmlTag({tagName:"a",attrs:this.createAttrs(t.getType(),t.getAnchorHref()),innerHtml:this.processAnchorText(t.getAnchorText())})},createAttrs:function(e,t){var n={href:t},r=this.createCssClass(e);return r&&(n.class=r),this.newWindow&&(n.target="_blank"),n},createCssClass:function(e){var t=this.className;return t?t+" "+t+"-"+e:""},processAnchorText:function(e){return e=this.doTruncate(e)},doTruncate:function(t){return e.Util.ellipsis(t,this.truncate||Number.POSITIVE_INFINITY)}}),e.htmlParser.HtmlParser=e.Util.extend(Object,{htmlRegex:function(){var e=/[0-9a-zA-Z][0-9a-zA-Z:]*/,t=/[^\s\0"'>\/=\x01-\x1F\x7F]+/,n=/(?:"[^"]*?"|'[^']*?'|[^'"=<>`\s]+)/,r=t.source+"(?:\\s*=\\s*"+n.source+")?";return new RegExp(["(?:","<(!DOCTYPE)","(?:","\\s+","(?:",r,"|",n.source+")",")*",">",")","|","(?:","<(/)?","("+e.source+")","(?:","\\s+",r,")*","\\s*/?",">",")"].join(""),"gi")}(),htmlCharacterEntitiesRegex:/( | |<|<|>|>|"|"|')/gi,parse:function(e){for(var t,n,r=this.htmlRegex,i=0,o=[];null!==(t=r.exec(e));){var a=t[0],s=t[1]||t[3]Line truncated
|
||||
* Bowser - a browser detector
|
||||
* https://github.com/ded/bowser
|
||||
* MIT License | (c) Dustin Diaz 2015
|
||||
*/
|
||||
!function(t,r,i){void 0!==e&&e.exports?e.exports=i():n(1209)("bowser",i)}(0,0,function(){function e(e){function t(t){var n=e.match(t);return n&&n.length>1&&n[1]||""}function n(t){var n=e.match(t);return n&&n.length>1&&n[2]||""}var r,i=t(/(ipod|iphone|ipad)/i).toLowerCase(),o=/like android/i.test(e),s=!o&&/android/i.test(e),u=/nexus\s*[0-6]\s*/i.test(e),l=!u&&/nexus\s*[0-9]+/i.test(e),c=/CrOS/.test(e),p=/silk/i.test(e),f=/sailfish/i.test(e),h=/tizen/i.test(e),d=/(web|hpw)os/i.test(e),m=/windows phone/i.test(e),v=(/SamsungBrowser/i.test(e),!m&&/windows/i.test(e)),g=!i&&!p&&/macintosh/i.test(e),y=!s&&!f&&!h&&!d&&/linux/i.test(e),_=n(/edg([ea]|ios)\/(\d+(\.\d+)?)/i),b=t(/version\/(\d+(\.\d+)?)/i),x=/tablet/i.test(e)&&!/tablet pc/i.test(e),w=!x&&/[^-]mobi/i.test(e),k=/xbox/i.test(e);/opera/i.test(e)?r={name:"Opera",opera:a,version:b||t(/(?:opera|opr|opios)[\s\/](\d+(\.\d+)?)/i)}:/opr\/|opios/i.test(e)?r={name:"Opera",opera:a,version:t(/(?:opr|opios)[\s\/](\d+(\.\d+)?)/i)||b}:/SamsungBrowser/i.test(e)?r={name:"Samsung Internet for Android",samsungBrowser:a,version:b||t(/(?:SamsungBrowser)[\s\/](\d+(\.\d+)?)/i)}:/coast/i.test(e)?r={name:"Opera Coast",coast:a,version:b||t(/(?:coast)[\s\/](\d+(\.\d+)?)/i)}:/yabrowser/i.test(e)?r={name:"Yandex Browser",yandexbrowser:a,version:b||t(/(?:yabrowser)[\s\/](\d+(\.\d+)?)/i)}:/ucbrowser/i.test(e)?r={name:"UC Browser",ucbrowser:a,version:t(/(?:ucbrowser)[\s\/](\d+(?:\.\d+)+)/i)}:/mxios/i.test(e)?r={name:"Maxthon",maxthon:a,version:t(/(?:mxios)[\s\/](\d+(?:\.\d+)+)/i)}:/epiphany/i.test(e)?r={name:"Epiphany",epiphany:a,version:t(/(?:epiphany)[\s\/](\d+(?:\.\d+)+)/i)}:/puffin/i.test(e)?r={name:"Puffin",puffin:a,version:t(/(?:puffin)[\s\/](\d+(?:\.\d+)?)/i)}:/sleipnir/i.test(e)?r={name:"Sleipnir",sleipnir:a,version:t(/(?:sleipnir)[\s\/](\d+(?:\.\d+)+)/i)}:/k-meleon/i.test(e)?r={name:"K-Meleon",kMeleon:a,version:t(/(?:k-meleon)[\s\/](\d+(?:\.\d+)+)/i)}:m?(r={name:"Windows Phone",osname:"Windows Phone",windowsphone:a},_?(r.msedge=a,r.version=_):(r.msie=a,r.version=t(/iemobile\/(\d+(\.\d+)?)/i))):/msie|trident/i.test(e)?r={name:"Internet Explorer",msie:a,version:t(/(?:msie |rv:)(\d+(\.\d+)?)/i)}:c?r={name:"Chrome",osname:"Chrome OS",chromeos:a,chromeBook:a,chrome:a,version:t(/(?:chrome|crios|crmo)\/(\d+(\.\d+)?)/i)}:/edg([ea]|ios)/i.test(e)?r={name:"Microsoft Edge",msedge:a,version:_}:/vivaldi/i.test(e)?r={name:"Vivaldi",vivaldi:a,version:t(/vivaldi\/(\d+(\.\d+)?)/i)||b}:f?r={name:"Sailfish",osname:"Sailfish OS",sailfish:a,version:t(/sailfish\s?browser\/(\d+(\.\d+)?)/i)}:/seamonkey\//i.test(e)?r={name:"SeaMonkey",seamonkey:a,version:t(/seamonkey\/(\d+(\.\d+)?)/i)}:/firefox|iceweasel|fxios/i.test(e)?(r={name:"Firefox",firefox:a,version:t(/(?:firefox|iceweasel|fxios)[ \/](\d+(\.\d+)?)/i)},/\((mobile|tablet);[^\)]*rv:[\d\.]+\)/i.test(e)&&(r.firefoxos=a,r.osname="Firefox OS")):p?r={name:"Amazon Silk",silk:a,version:t(/silk\/(\d+(\.\d+)?)/i)}:/phantom/i.test(e)?r={name:"PhantomJS",phantom:a,version:t(/phantomjs\/(\d+(\.\d+)?)/i)}:/slimerjs/i.test(e)?r={name:"SlimerJS",slimer:a,version:t(/slimerjs\/(\d+(\.\d+)?)/i)}:/blackberry|\bbb\d+/i.test(e)||/rim\stablet/i.test(e)?r={name:"BlackBerry",osname:"BlackBerry OS",blackberry:a,version:b||t(/blackberry[\d]+\/(\d+(\.\d+)?)/i)}:d?(r={name:"WebOS",osname:"WebOS",webos:a,version:b||t(/w(?:eb)?osbrowser\/(\d+(\.\d+)?)/i)},/touchpad\//i.test(e)&&(r.touchpad=a)):/bada/i.test(e)?r={name:"Bada",osname:"Bada",bada:a,version:t(/dolfin\/(\d+(\.\d+)?)/i)}:h?r={name:"Tizen",osname:"Tizen",tizen:a,version:t(/(?:tizen\s?)?browser\/(\d+(\.\d+)?)/i)||b}:/qupzilla/i.test(e)?r={name:"QupZilla",qupzilla:a,version:t(/(?:qupzilla)[\s\/](\d+(?:\.\d+)+)/i)||b}:/chromium/i.test(e)?r={name:"Chromium",chromium:a,version:t(/(?:chromium)[\s\/](\d+(?:\.\d+)?)/i)||b}:/chrome|crios|crmo/i.test(e)?r={name:"Chrome",chrome:a,version:t(/(?:chrome|crios|crmo)\/(\d+(\.\d+)?)/i)}:s?r={name:"Android",version:b}:/safari|applewebkit/i.test(e)?(r={name:"Safari",safari:a},b&&(r.version=b)):i?(r={name:"iphone"==i?"iPhone":"ipad"==i?"iPad":"iPod"},b&&(r.version=b)):r=/googlebot/i.test(e)?{name:"Googlebot",googlebot:a,version:t(/googlebot\/(\d+(\.\d+))/i)||b}:{name:t(/^(.*)\/(.*) /),version:n(/^(.*)\/(.*) /)},!r.msedge&&/(apple)?webkit/i.test(e)?(/(apple)?webkit\/537\.36/i.test(e)?(r.name=r.name||"Blink",r.blink=a):(r.name=r.name||"Webkit",r.webkit=a),!r.version&&b&&(r.version=b)):!r.opera&&/gecko\//i.test(e)&&(r.name=r.name||"Gecko",r.gecko=a,r.version=r.version||t(/gecko\/(\d+(\.\d+)?)/i)),r.windowsphone||!s&&!r.silk?!r.windowsphone&&i?(r[i]=a,r.ios=a,r.osname="iOS"):g?(r.mac=a,r.osname="macOS"):k?(r.xbox=a,r.osname="Xbox"):v?(r.windows=a,r.osname="Windows"):y&&(r.linux=a,r.osname="Linux"):(r.android=a,r.osname="Android");var E="";r.windows?E=function(e){switch(e){case"NT":return"NT";case"XP":return"XP";case"NT 5.0":return"2000";case"NT 5.1":return"XP";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.Line truncated
|
||||
Copyright (c) 2016 Jed Watson.
|
||||
Licensed under the MIT License (MIT), see
|
||||
http://jedwatson.github.io/classnames
|
||||
*/
|
||||
!function(){"use strict";function n(){for(var e=[],t=0;t<arguments.length;t++){var r=arguments[t];if(r){var i=typeof r;if("string"===i||"number"===i)e.push(r);else if(Array.isArray(r))e.push(n.apply(null,r));else if("object"===i)for(var a in r)o.call(r,a)&&r[a]&&e.push(a)}}return e.join(" ")}var o={}.hasOwnProperty;void 0!==e&&e.exports?e.exports=n:(r=[],void 0!==(i=function(){return n}.apply(t,r))&&(e.exports=i))}()},function(e,t,n){"use strict";function r(e){return{key:e.nodeKey,className:e.className,"data-sourcepos":e["data-sourcepos"]}}function i(e){var t=e.toLowerCase(),n=w[t]||t;return void 0!==k[n]?n:e}function o(e){return Object.keys(e||{}).reduce(function(t,n){return t[i(n)]=e[n],t},{})}function a(e){var t=r(e),n=e.escapeHtml?{}:{dangerouslySetInnerHTML:{__html:e.literal}},i=e.escapeHtml?[e.literal]:null;if(e.escapeHtml||!e.skipHtml){var o=y(t,n);return l(e.isBlock?"div":"span",o,i)}}function s(e){var t=e.parent.parent;return t&&"list"===t.type.toLowerCase()&&t.listTight}function u(e,t){var n=e;do{n=n.parent}while(!n.react);n.react.children.push(t)}function l(e,t,n){var r=Array.isArray(n)&&n.reduce(c,[]),i=[e,t].concat(r||n);return g.createElement.apply(g,i)}function c(e,t){var n=e.length-1;return"string"==typeof t&&"string"==typeof e[n]?e[n]+=t:e.push(t),e}function p(e){return[e[0][0],":",e[0][1],"-",e[1][0],":",e[1][1]].map(String).join("")}function f(e,t,n,r){var o={key:t};n.sourcePos&&e.sourcepos&&(o["data-sourcepos"]=p(e.sourcepos));var a=i(e.type);switch(a){case"html_inline":case"html_block":o.isBlock="html_block"===a,o.escapeHtml=n.escapeHtml,o.skipHtml=n.skipHtml;break;case"code_block":var s=e.info?e.info.split(/ +/):[];s.length>0&&s[0].length>0&&(o.language=s[0],o.codeinfo=s);break;case"code":o.children=e.literal,o.inline=!0;break;case"heading":o.level=e.level;break;case"softbreak":o.softBreak=n.softBreak;break;case"link":o.href=n.transformLinkUri?n.transformLinkUri(e.destination):e.destination,o.title=e.title||void 0,n.linkTarget&&(o.target=n.linkTarget);break;case"image":o.src=n.transformImageUri?n.transformImageUri(e.destination):e.destination,o.title=e.title||void 0,o.alt=e.react.children.join(""),e.react.children=void 0;break;case"list":o.start=e.listStart,o.type=e.listType,o.tight=e.listTight}"string"!=typeof r&&(o.literal=e.literal);var u=o.children||e.react&&e.react.children;return Array.isArray(u)&&(o.children=u.reduce(c,[])||null),o}function h(e){return e?e.sourcepos?p(e.sourcepos):h(e.parent):null}function d(e){for(var t,n,r,o,a,l,c,p,d,m=e.walker(),v={sourcePos:this.sourcePos,escapeHtml:this.escapeHtml,skipHtml:this.skipHtml,transformLinkUri:this.transformLinkUri,transformImageUri:this.transformImageUri,softBreak:this.softBreak,linkTarget:this.linkTarget},_=0;t=m.next();){var b=h(t.node.sourcepos?t.node:t.node.parent);if(d===b?(c=b+_,_++):(c=b,_=0),d=b,r=t.entering,o=!r,n=t.node,a=i(n.type),p=null,l){if(n!==l&&!("paragraph"===a&&s(n)||this.skipHtml&&("html_block"===a||"html_inline"===a))){var w=n===l,k=-1===this.allowedTypes.indexOf(a),E=!1,S=n.isContainer&&o,C=this.renderers[a];if(this.allowNode&&(S||!n.isContainer)){var A=S?n.react.children:[];p=f(n,c,v,C),E=!this.allowNode({type:x(a),renderer:this.renderers[a],props:p,children:A})}if(w||!E&&!k){var D="text"===a||"softbreak"===a;if("function"!=typeof C&&!D&&"string"!=typeof C)throw new Error("Renderer for type `"+x(n.type)+"` not defined or is not renderable");if(n.isContainer&&r)n.react={component:C,props:{},children:[]};else{var O=p||f(n,c,v,C);if(C)O="string"==typeof C?O:y(O,{nodeKey:O.key}),u(n,g.createElement(C,O));else if("text"===a)u(n,n.literal);else if("softbreak"===a){var M="br"===this.softBreak?g.createElement("br",{key:c}):this.softBreak;u(n,M)}}}else!this.unwrapDisallowed&&r&&n.isContainer&&m.resumeAt(n,!1)}}else l=n,n.react={children:[]}}return l.react.children}function m(e){var t=e.replace(/file:\/\//g,"x-file://");return decodeURI(b.uriInDoubleQuotedAttr(t))}function v(e){var t=e||{};if(t.allowedTypes&&t.disallowedTypes)throw new Error("Only one of `allowedTypes` and `disallowedTypes` should be defined");if(t.allowedTypes&&!Array.isArray(t.allowedTypes))throw new Error("`allowedTypes` must be an array");if(t.disallowedTypes&&!Array.isArray(t.disallowedTypes))throw new Error("`disallowedTypes` must be an array");if(t.allowNode&&"function"!=typeof t.allowNode)throw new Error("`allowNode` must be a function");var n=t.transformLinkUri;if(void 0===n)n=m;else if(n&&"function"!=typeof n)throw new Error("`transformLinkUri` must either be a function, or `null` to disable");var r=t.transformImageUri;if(void 0!==r&&"function"!=typeof r)throw new Error("`transformImageUri` must be a function");if(t.renderers&&!_(t.renderers))throw new Error("`renderers` must be a plain object of `Type`: `Renderer` pairs");var a=t.allowedTypes&&t.allowedTypes.map(i)||E;if(t.disallowedTypes){var s=t.disallowedTypes.map(i);a=a.filter(function(e){return-1===s.indexOf(e)})}return{sourcePos:Boolean(t.sourcePos),softBreak:t.softBreak||"\n",rendLine truncated
|
||||
if(String.fromCodePoint)e.exports=function(e){try{return String.fromCodePoint(e)}catch(e){if(e instanceof RangeError)return String.fromCharCode(65533);throw e}};else{var r=String.fromCharCode,i=Math.floor,o=function(){var e,t,n=[],o=-1,a=arguments.length;if(!a)return"";for(var s="";++o<a;){var u=Number(arguments[o]);if(!isFinite(u)||u<0||u>1114111||i(u)!==u)return String.fromCharCode(65533);u<=65535?n.push(u):(u-=65536,e=55296+(u>>10),t=u%1024+56320,n.push(e,t)),(o+1===a||n.length>16384)&&(s+=r.apply(null,n),n.length=0)}return s};e.exports=o}},function(e,t,n){"use strict";e.exports.Node=n(177),e.exports.Parser=n(588),e.exports.HtmlRenderer=n(593),e.exports.XmlRenderer=n(594)},function(e,t,n){"use strict";function r(e){return{subject:"",delimiters:null,brackets:null,pos:0,refmap:{},match:N,peek:F,spnl:B,parseBackticks:L,parseBackslash:q,parseAutolink:z,parseHtmlTag:U,scanDelims:W,handleDelim:V,parseLinkTitle:K,parseLinkDestination:X,parseLinkLabel:Y,parseOpenBracket:$,parseBang:Z,parseCloseBracket:Q,addBracket:ee,removeBracket:te,parseEntity:ne,parseString:re,parseNewline:ie,parseReference:oe,parseInline:ae,processEmphasis:G,removeDelimiter:H,options:e||{},parse:se}}var i=n(177),o=n(73),a=n(592),s=o.normalizeURI,u=o.unescapeString,l=n(589),c=n(113).decodeHTML;n(507);var p=o.ESCAPABLE,f="\\\\"+p,h=o.ENTITY,d=o.reHtmlTag,m=new RegExp(/[!"#$%&'()*+,\-.\/:;<=>?@\[\]^_`{|}~\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u0AF0\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E42\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC9\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDF3C-\uDF3E]|\uD809[\uDC70-\uDC74]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]/),v=new RegExp('^(?:"('+f+'|[^"\\x00])*"|\'('+f+"|[^'\\x00])*'|\\(("+f+"|[^)\\x00])*\\))"),g=new RegExp("^(?:[<](?:[^ <>\\t\\n\\\\\\x00]|"+f+"|\\\\)*[>])"),y=new RegExp("^"+p),_=new RegExp("^"+h,"i"),b=/`+/,x=/^`+/,w=/\.\.\./g,k=/--+/g,E=/^<([a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)>/,S=/^<[A-Za-z][A-Za-z0-9.+-]{1,31}:[^<>\x00-\x20]*>/i,C=/^ *(?:\n *)?/,A=/^[ \t\n\x0b\x0c\x0d]/,D=/[ \t\n\x0b\x0c\x0d]+/g,O=/^\s/,M=/ *$/,T=/^ */,P=/^ *(?:\n|$)/,I=new RegExp("^\\[(?:[^\\\\\\[\\]]|"+f+"|\\\\){0,1000}\\]"),R=/^[^\n`\[\]\\!<&*_'"]+/m,j=function(e){var t=new i("text");return t._literal=e,t},N=function(e){var t=e.exec(this.subject.slice(this.pos));return null===t?null:(this.pos+=t.index+t[0].length,t[0])},F=function(){return this.pos<this.subject.length?this.subject.charCodeAt(this.pos):-1},B=function(){return this.match(C),!0},L=function(e){var t=this.match(x);if(null===t)return!1;for(var n,r,o=this.pos;null!==(n=this.match(b));)if(n===t)return r=new i("code"),r._literal=this.subject.slice(o,this.pos-t.length).trim().replace(D," "),e.appendChild(r),!0;return this.pos=o,e.appendChild(j(t)),!0},q=function(e){var t,n=this.subject;return this.pos+=1,10===this.peek()?(this.pos+=1,t=new i("linebreak"),e.appendChild(t)):y.test(n.charAt(this.pos))?(e.appendChild(j(n.charAt(this.pos))),this.pos+=1):e.appendChild(j("\\")),!0},z=function(e){var t,n,r;return(t=this.match(E))?(n=t.slice(1,t.length-1),r=new i("link"),r._destination=s("mailto:"+n),r._title="",r.appendChild(j(n)),e.appendChild(r),!0):!!(t=this.match(S))&&(n=t.slice(1,t.length-1),r=new i("link"),r._destination=s(n),r._title="",r.appendChild(j(n)),e.appendChild(r),!0)},U=function(e){var t=this.match(d);if(null===t)return!1;var n=new i("html_inline");return n._literal=t,e.appendChild(n),!0},W=function(e){var t,n,r,i,o,a,s,u,c,p,f,h=0,d=this.pos;if(39===e||34===e)h++,this.pos++;else for(;this.peek()===eLine truncated
|
||||
* cookie
|
||||
* Copyright(c) 2012-2014 Roman Shtylman
|
||||
* Copyright(c) 2015 Douglas Christopher Wilson
|
||||
* MIT Licensed
|
||||
*/
|
||||
t.parse=r,t.serialize=i;var a=decodeURIComponent,s=encodeURIComponent,u=/; */,l=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/},function(e,t,n){n(692),n(696),n(703),n(373),n(687),n(688),n(693),n(697),n(699),n(683),n(684),n(685),n(686),n(689),n(690),n(691),n(694),n(695),n(698),n(700),n(701),n(702),n(679),n(680),n(681),n(682),e.exports=n(63).String},function(e,t,n){n(677),n(373),n(706),n(678),n(704),n(705),e.exports=n(63).Promise},function(e,t,n){n(103),n(634),e.exports=n(15).Array.from},function(e,t,n){n(104),n(103),e.exports=n(632)},function(e,t,n){n(104),n(103),e.exports=n(633)},function(e,t,n){var r=n(15),i=r.JSON||(r.JSON={stringify:JSON.stringify});e.exports=function(e){return i.stringify.apply(i,arguments)}},function(e,t,n){n(636),e.exports=n(15).Object.assign},function(e,t,n){n(637);var r=n(15).Object;e.exports=function(e,t){return r.create(e,t)}},function(e,t,n){n(638);var r=n(15).Object;e.exports=function(e,t,n){return r.defineProperty(e,t,n)}},function(e,t,n){n(639),e.exports=n(15).Object.getPrototypeOf},function(e,t,n){n(640),e.exports=n(15).Object.keys},function(e,t,n){n(641),e.exports=n(15).Object.setPrototypeOf},function(e,t,n){n(197),n(103),n(104),n(642),n(645),n(646),e.exports=n(15).Promise},function(e,t,n){n(643),n(197),n(647),n(648),e.exports=n(15).Symbol},function(e,t,n){n(103),n(104),e.exports=n(195).f("iterator")},function(e,t,n){n(197),n(104),n(644),n(650),n(649),e.exports=n(15).WeakMap},function(e,t){e.exports=function(){}},function(e,t,n){var r=n(75),i=n(132),o=n(631);e.exports=function(e){return function(t,n,a){var s,u=r(t),l=i(u.length),c=o(a,l);if(e&&n!=n){for(;l>c;)if((s=u[c++])!=s)return!0}else for(;l>c;c++)if((e||c in u)&&u[c]===n)return e||c||0;return!e&&-1}}},function(e,t,n){var r=n(29),i=n(344),o=n(21)("species");e.exports=function(e){var t;return i(e)&&(t=e.constructor,"function"!=typeof t||t!==Array&&!i(t.prototype)||(t=void 0),r(t)&&null===(t=t[o])&&(t=void 0)),void 0===t?Array:t}},function(e,t,n){var r=n(614);e.exports=function(e,t){return new(r(e))(t)}},function(e,t,n){"use strict";var r=n(188),i=n(130).getWeak,o=n(38),a=n(29),s=n(178),u=n(128),l=n(179),c=n(56),p=n(358),f=l(5),h=l(6),d=0,m=function(e){return e._l||(e._l=new v)},v=function(){this.a=[]},g=function(e,t){return f(e.a,function(e){return e[0]===t})};v.prototype={get:function(e){var t=g(this,e);if(t)return t[1]},has:function(e){return!!g(this,e)},set:function(e,t){var n=g(this,e);n?n[1]=t:this.a.push([e,t])},delete:function(e){var t=h(this.a,function(t){return t[0]===e});return~t&&this.a.splice(t,1),!!~t}},e.exports={getConstructor:function(e,t,n,o){var l=e(function(e,r){s(e,l,t,"_i"),e._t=t,e._i=d++,e._l=void 0,void 0!=r&&u(r,n,e[o],e)});return r(l.prototype,{delete:function(e){if(!a(e))return!1;var n=i(e);return!0===n?m(p(this,t)).delete(e):n&&c(n,this._i)&&delete n[this._i]},has:function(e){if(!a(e))return!1;var n=i(e);return!0===n?m(p(this,t)).has(e):n&&c(n,this._i)}}),l},def:function(e,t,n){var r=i(o(t),!0);return!0===r?m(e).set(t,n):r[e._i]=n,e},ufstore:m}},function(e,t,n){"use strict";var r=n(24),i=n(23),o=n(130),a=n(55),s=n(57),u=n(188),l=n(128),c=n(178),p=n(29),f=n(102),h=n(44).f,d=n(179)(0),m=n(49);e.exports=function(e,t,n,v,g,y){var _=r[e],b=_,x=g?"set":"add",w=b&&b.prototype,k={};return m&&"function"==typeof b&&(y||w.forEach&&!a(function(){(new b).entries().next()}))?(b=t(function(t,n){c(t,b,e,"_c"),t._c=new _,void 0!=n&&l(n,g,t[x],t)}),d("add,clear,delete,forEach,get,has,set,keys,values,entries,toJSON".split(","),function(e){var t="add"==e||"set"==e;e in w&&(!y||"clear"!=e)&&s(b.prototype,e,function(n,r){if(c(this,b,e),!t&&y&&!p(n))return"get"==e&&void 0;var i=this._c[e](0===n?0:n,r);return t?this:i})}),y||h(b.prototype,"size",{get:function(){return this._c.size}})):(b=v.getConstructor(t,e,g,x),u(b.prototype,n),o.NEED=!0),f(b,e),k[e]=b,i(i.G+i.W+i.F,k),y||v.setStrong(b,e,g),b}},function(e,t,n){"use strict";var r=n(44),i=n(101);e.exports=function(e,t,n){t in e?r.f(e,t,i(0,n)):e[t]=n}},function(e,t,n){var r=n(100),i=n(187),o=n(131);e.exports=function(e){var t=r(e),n=i.f;if(n)for(var a,s=n(e),u=o.f,l=0;s.length>l;)u.call(e,a=s[l++])&&t.push(a);return t}},function(e,t){e.exports=function(e,t,n){var r=void 0===n;switch(t.length){case 0:return r?e():e.call(n);case 1:return r?e(t[0]):e.call(n,t[0]);case 2:return r?e(t[0],t[1]):e.call(n,t[0],t[1]);case 3:return r?e(t[0],t[1],t[2]):e.call(n,t[0],t[1],t[2]);case 4:return r?e(t[0],t[1],t[2],t[3]):e.call(n,t[0],t[1],t[2],t[3])}return e.apply(n,t)}},function(e,t,n){"use strict";var r=n(186),i=n(101),o=n(102),a={};n(57)(a,n(21)("iterator"),function(){return this}),e.exports=function(e,t,n){e.prototype=r(a,{next:i(1,n)}),o(e,t+" Iterator")}},function(e,t){e.exports=function(e,t){return{value:t,done:!!e}}},function(e,t,n){var r=n(24),i=n(357).set,o=r.MutationObserver||r.WebKitMutationObserver,a=r.process,s=r.Promise,u="process"==n(99)(a);e.exports=function(){var e,t,n,l=function(){var r,i;for(u&&(r=a.domain)&&r.exit();e;){i=e.fn,e=e.next;try{i()}catch(r){throw e?n():t=vLine truncated
|
||||
* pascalcase <https://github.com/jonschlinkert/pascalcase>
|
||||
*
|
||||
* Copyright (c) 2015, Jon Schlinkert.
|
||||
* Licensed under the MIT License.
|
||||
*/
|
||||
function n(e){if("string"!=typeof e)throw new TypeError("expected a string.");return e=e.replace(/([A-Z])/g," $1"),1===e.length?e.toUpperCase():(e=e.replace(/^[\W_]+|[\W_]+$/g,"").toLowerCase(),e=e.charAt(0).toUpperCase()+e.slice(1),e.replace(/[\W_]+(\w|$)/g,function(e,t){return t.toUpperCase()}))}e.exports=n},function(e,t,n){"use strict";(function(r){function i(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}t.__esModule=!0;var a=n(455),s=i(a),u=n(234),l=i(u),c=function(){function e(t,n,r){o(this,e),this.stringify=t,this.mapOpts=r.map||{},this.root=n,this.opts=r}return e.prototype.isMap=function(){return void 0!==this.opts.map?!!this.opts.map:this.previous().length>0},e.prototype.previous=function(){var e=this;return this.previousMaps||(this.previousMaps=[],this.root.walk(function(t){if(t.source&&t.source.input.map){var n=t.source.input.map;-1===e.previousMaps.indexOf(n)&&e.previousMaps.push(n)}})),this.previousMaps},e.prototype.isInline=function(){if(void 0!==this.mapOpts.inline)return this.mapOpts.inline;var e=this.mapOpts.annotation;return(void 0===e||!0===e)&&(!this.previous().length||this.previous().some(function(e){return e.inline}))},e.prototype.isSourcesContent=function(){return void 0!==this.mapOpts.sourcesContent?this.mapOpts.sourcesContent:!this.previous().length||this.previous().some(function(e){return e.withContent()})},e.prototype.clearAnnotation=function(){if(!1!==this.mapOpts.annotation)for(var e=void 0,t=this.root.nodes.length-1;t>=0;t--)e=this.root.nodes[t],"comment"===e.type&&0===e.text.indexOf("# sourceMappingURL=")&&this.root.removeChild(t)},e.prototype.setSourcesContent=function(){var e=this,t={};this.root.walk(function(n){if(n.source){var r=n.source.input.from;if(r&&!t[r]){t[r]=!0;var i=e.relative(r);e.map.setSourceContent(i,n.source.input.css)}}})},e.prototype.applyPrevMaps=function(){for(var e=this.previous(),t=Array.isArray(e),n=0,e=t?e:e[Symbol.iterator]();;){var r;if(t){if(n>=e.length)break;r=e[n++]}else{if(n=e.next(),n.done)break;r=n.value}var i=r,o=this.relative(i.file),a=i.root||l.default.dirname(i.file),u=void 0;!1===this.mapOpts.sourcesContent?(u=new s.default.SourceMapConsumer(i.text),u.sourcesContent&&(u.sourcesContent=u.sourcesContent.map(function(){return null}))):u=i.consumer(),this.map.applySourceMap(u,o,this.relative(a))}},e.prototype.isAnnotation=function(){return!!this.isInline()||(void 0!==this.mapOpts.annotation?this.mapOpts.annotation:!this.previous().length||this.previous().some(function(e){return e.annotation}))},e.prototype.toBase64=function(e){return r?r.from&&r.from!==Uint8Array.from?r.from(e).toString("base64"):new r(e).toString("base64"):window.btoa(unescape(encodeURIComponent(e)))},e.prototype.addAnnotation=function(){var e=void 0;e=this.isInline()?"data:application/json;base64,"+this.toBase64(this.map.toString()):"string"==typeof this.mapOpts.annotation?this.mapOpts.annotation:this.outputFile()+".map";var t="\n";-1!==this.css.indexOf("\r\n")&&(t="\r\n"),this.css+=t+"/*# sourceMappingURL="+e+" */"},e.prototype.outputFile=function(){return this.opts.to?this.relative(this.opts.to):this.opts.from?this.relative(this.opts.from):"to.css"},e.prototype.generateMap=function(){return this.generateString(),this.isSourcesContent()&&this.setSourcesContent(),this.previous().length>0&&this.applyPrevMaps(),this.isAnnotation()&&this.addAnnotation(),this.isInline()?[this.css]:[this.css,this.map]},e.prototype.relative=function(e){if(0===e.indexOf("<"))return e;if(/^\w+:\/\//.test(e))return e;var t=this.opts.to?l.default.dirname(this.opts.to):".";return"string"==typeof this.mapOpts.annotation&&(t=l.default.dirname(l.default.resolve(t,this.mapOpts.annotation))),e=l.default.relative(t,e),"\\"===l.default.sep?e.replace(/\\/g,"/"):e},e.prototype.sourcePath=function(e){return this.mapOpts.from?this.mapOpts.from:this.relative(e.source.input.from)},e.prototype.generateString=function(){var e=this;this.css="",this.map=new s.default.SourceMapGenerator({file:this.outputFile()});var t=1,n=1,r=void 0,i=void 0;this.stringify(this.root,function(o,a,s){e.css+=o,a&&"end"!==s&&(a.source&&a.source.start?e.map.addMapping({source:e.sourcePath(a),generated:{line:t,column:n-1},original:{line:a.source.start.line,column:a.source.start.column-1}}):e.map.addMapping({source:"<no source>",original:{line:1,column:0},generated:{line:t,column:n-1}})),r=o.match(/\n/g),r?(t+=r.length,i=o.lastIndexOf("\n"),n=o.length-i):n+=o.length,a&&"start"!==s&&(a.source&&a.source.end?e.map.addMapping({source:e.sourcePath(a),generated:{line:t,column:n-1},original:{line:a.source.end.line,column:a.source.end.column}}):e.map.addMapping({source:"<no source>",original:{line:1,column:0},generated:{line:t,column:n-1}}))})},e.prototype.generate=function(){if(this.clearAnnotation(),this.isMap())return this.generateMap();var e="";return this.stringify(this.root,function(t){e+=t}),[e]},e}();t.default=c,e.exports=t.default}).call(t,n(43).Buffer)},Line truncated
|
||||
if(String.fromCodePoint)e.exports=function(e){try{return String.fromCodePoint(e)}catch(e){if(e instanceof RangeError)return String.fromCharCode(65533);throw e}};else{var r=String.fromCharCode,i=Math.floor,o=function(){var e,t,n=[],o=-1,a=arguments.length;if(!a)return"";for(var s="";++o<a;){var u=Number(arguments[o]);if(!isFinite(u)||u<0||u>1114111||i(u)!==u)return String.fromCharCode(65533);u<=65535?n.push(u):(u-=65536,e=55296+(u>>10),t=u%1024+56320,n.push(e,t)),(o+1===a||n.length>16384)&&(s+=r.apply(null,n),n.length=0)}return s};e.exports=o}},function(e,t,n){"use strict";function r(e){return{softbreak:"\n",escape:i,options:e||{},render:c}}var i=n(91).escapeXml,o=function(e,t,n){var r="<"+e;if(t&&t.length>0)for(var i,o=0;void 0!==(i=t[o]);)r+=" "+i[0]+'="'+i[1]+'"',o++;return n&&(r+=" /"),r+=">"},a=/\<[^>]*\>/,s=/^javascript:|vbscript:|file:|data:/i,u=/^data:image\/(?:png|gif|jpeg|webp)/i,l=function(e){return s.test(e)&&!u.test(e)},c=function(e){var t,n,r,i,s,u,c,p=e.walker(),f="",h="\n",d=0,m=function(e){f+=d>0?e.replace(a,""):e,h=e},v=this.escape,g=function(){"\n"!==h&&(f+="\n",h="\n")},y=this.options;for(y.time&&console.time("rendering");i=p.next();){if(u=i.entering,s=i.node,t=[],y.sourcepos){var _=s.sourcepos;_&&t.push(["data-sourcepos",String(_[0][0])+":"+String(_[0][1])+"-"+String(_[1][0])+":"+String(_[1][1])])}switch(s.type){case"Text":m(v(s.literal,!1));break;case"Softbreak":m(this.softbreak);break;case"Hardbreak":m(o("br",[],!0)),g();break;case"Emph":m(o(u?"em":"/em"));break;case"Strong":m(o(u?"strong":"/strong"));break;case"HtmlInline":m(y.safe?"\x3c!-- raw HTML omitted --\x3e":s.literal);break;case"CustomInline":u&&s.onEnter?m(s.onEnter):!u&&s.onExit&&m(s.onExit);break;case"Link":u?(y.safe&&l(s.destination)||t.push(["href",v(s.destination,!0)]),s.title&&t.push(["title",v(s.title,!0)]),m(o("a",t))):m(o("/a"));break;case"Image":u?(0===d&&m(y.safe&&l(s.destination)?'<img src="" alt="':'<img src="'+v(s.destination,!0)+'" alt="'),d+=1):0===(d-=1)&&(s.title&&m('" title="'+v(s.title,!0)),m('" />'));break;case"Code":m(o("code")+v(s.literal,!1)+o("/code"));break;case"Document":break;case"Paragraph":if(null!==(c=s.parent.parent)&&"List"===c.type&&c.listTight)break;u?(g(),m(o("p",t))):(m(o("/p")),g());break;case"BlockQuote":u?(g(),m(o("blockquote",t)),g()):(g(),m(o("/blockquote")),g());break;case"Item":u?m(o("li",t)):(m(o("/li")),g());break;case"List":if(r="Bullet"===s.listType?"ul":"ol",u){var b=s.listStart;null!==b&&1!==b&&t.push(["start",b.toString()]),g(),m(o(r,t)),g()}else g(),m(o("/"+r)),g();break;case"Heading":r="h"+s.level,u?(g(),m(o(r,t))):(m(o("/"+r)),g());break;case"CodeBlock":n=s.info?s.info.split(/\s+/):[],n.length>0&&n[0].length>0&&t.push(["class","language-"+v(n[0],!0)]),g(),m(o("pre")+o("code",t)),m(v(s.literal,!1)),m(o("/code")+o("/pre")),g();break;case"HtmlBlock":g(),m(y.safe?"\x3c!-- raw HTML omitted --\x3e":s.literal),g();break;case"CustomBlock":g(),u&&s.onEnter?m(s.onEnter):!u&&s.onExit&&m(s.onExit),g();break;case"ThematicBreak":g(),m(o("hr",t,!0)),g();break;default:throw"Unknown node type "+s.type}}return y.time&&console.timeEnd("rendering"),f};e.exports=r},function(e,t,n){"use strict";e.exports.version="0.24.0",e.exports.Node=n(260),e.exports.Parser=n(1088),e.exports.HtmlRenderer=n(1090),e.exports.XmlRenderer=n(1094)},function(e,t,n){"use strict";function r(e){return{subject:"",delimiters:null,pos:0,refmap:{},match:F,peek:B,spnl:L,parseBackticks:q,parseBackslash:z,parseAutolink:U,parseHtmlTag:W,scanDelims:V,handleDelim:H,parseLinkTitle:X,parseLinkDestination:Y,parseLinkLabel:$,parseOpenBracket:Z,parseCloseBracket:ee,parseBang:Q,parseEntity:te,parseString:ne,parseNewline:re,parseReference:ie,parseInline:oe,processEmphasis:K,removeDelimiter:J,options:e||{},parse:ae}}var i=n(260),o=n(91),a=n(1093),s=o.normalizeURI,u=o.unescapeString,l=n(1089),c=n(113).decodeHTML;n(507);var p=o.ESCAPABLE,f="\\\\"+p,h="\\(([^\\\\()\\x00-\\x20]|"+f+"|\\\\)*\\)",d=o.ENTITY,m=o.reHtmlTag,v=new RegExp(/^[\u2000-\u206F\u2E00-\u2E7F\\'!"#\$%&\(\)\*\+,\-\.\/:;<=>\?@\[\]\^_`\{\|\}~]/),g=new RegExp('^(?:"('+f+'|[^"\\x00])*"|\'('+f+"|[^'\\x00])*'|\\(("+f+"|[^)\\x00])*\\))"),y=new RegExp("^(?:[<](?:[^ <>\\t\\n\\\\\\x00]|"+f+"|\\\\)*[>])"),_=new RegExp("^(?:[^\\\\()\\x00-\\x20]+|"+f+"|\\\\|"+h+")*"),b=new RegExp("^"+p),x=new RegExp("^"+d,"i"),w=/`+/,k=/^`+/,E=/\.\.\./g,S=/--+/g,C=/^<([a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)>/,A=/^<[A-Za-z][A-Za-z0-9.+-]{1,31}:[^<>\x00-\x20]*>/i,D=/^ *(?:\n *)?/,O=/^\s/,M=/\s+/g,T=/ *$/,P=/^ */,I=/^ *(?:\n|$)/,R=new RegExp("^\\[(?:[^\\\\\\[\\]]|"+f+"|\\\\){0,1000}\\]"),j=/^[^\n`\[\]\\!<&*_'"]+/m,N=function(e){var t=new i("Text");return t._literal=e,t},F=function(e){var t=e.exec(this.subject.slice(this.pos));return null===t?null:(this.pos+=t.index+t[0].length,t[0])},B=function(){return this.pos<this.subject.length?this.subject.charCodeAt(this.pos):-1},L=function(){return this.match(D),!0},q=funcLine truncated
|
||||
* repeat-string <https://github.com/jonschlinkert/repeat-string>
|
||||
*
|
||||
* Copyright (c) 2014-2015, Jon Schlinkert.
|
||||
* Licensed under the MIT License.
|
||||
*/
|
||||
var i,o="";e.exports=r},function(e,t,n){"use strict";e.exports=function(e,t){if(t=t.split(":")[0],!(e=+e))return!1;switch(t){case"http":case"ws":return 80!==e;case"https":case"wss":return 443!==e;case"ftp":return 21!==e;case"gopher":return 70!==e;case"file":return!1}return 0!==e}},function(e,t,n){"use strict";function r(e,t){e&&Object.keys(e).forEach(function(n){t(e[n],n)})}function i(e,t){return{}.hasOwnProperty.call(e,t)}function o(e,t){var n=[];return r(e,function(e){t(e)&&n.push(e)}),n}function a(e,t,n){function _(e,t){var n=this;this.tag=e,this.attribs=t||{},this.tagPosition=C.length,this.text="",this.updateParentNodeText=function(){if(R.length){R[R.length-1].text+=n.text}}}function b(e){return"string"!=typeof e&&(e+=""),e.replace(/\&/g,"&").replace(/</g,"<").replace(/\>/g,">").replace(/\"/g,""")}function x(e,n){n=n.replace(/[\x00-\x20]+/g,""),n=n.replace(/<\!\-\-.*?\-\-\>/g,"");var r=n.match(/^([a-zA-Z]+)\:/);if(!r)return!!n.match(/^[\/\\]{2}/)&&!t.allowProtocolRelative;var o=r[1].toLowerCase();return i(t.allowedSchemesByTag,e)?-1===t.allowedSchemesByTag[e].indexOf(o):!t.allowedSchemes||-1===t.allowedSchemes.indexOf(o)}function w(e,t){if(!t)return e;var n,r=c(e),i=e.nodes[0];return n=t[i.selector]&&t["*"]?p(c(t[i.selector]),t["*"],function(e,t){if(Array.isArray(e))return e.concat(t)}):t[i.selector]||t["*"],n&&(r.nodes[0].nodes=i.nodes.reduce(E(n),[])),r}function k(e){return e.nodes[0].nodes.reduce(function(e,t){return e.push(t.prop+":"+t.value+";"),e},[]).join("")}function E(e){return function(t,n){if(e.hasOwnProperty(n.prop)){e[n.prop].some(function(e){return e.test(n.value)})&&t.push(n)}return t}}function S(e,t){return t?(e=e.split(/\s+/),e.filter(function(e){return-1!==t.indexOf(e)}).join(" ")):e}var C="";t?(t=u(a.defaults,t),t.parser?t.parser=u(y,t.parser):t.parser=y):(t=a.defaults,t.parser=y);var A,D,O=t.nonTextTags||["script","style","textarea"];t.allowedAttributes&&(A={},D={},r(t.allowedAttributes,function(e,t){A[t]=[];var n=[];e.forEach(function(e){f(e)&&e.indexOf("*")>=0?n.push(l(e).replace(/\\\*/g,".*")):A[t].push(e)}),D[t]=new RegExp("^("+n.join("|")+")$")}));var M={};r(t.allowedClasses,function(e,t){A&&(i(A,t)||(A[t]=[]),A[t].push("class")),M[t]=e});var T,P={};r(t.transformTags,function(e,t){var n;"function"==typeof e?n=e:"string"==typeof e&&(n=a.simpleTransform(e)),"*"===t?T=n:P[t]=n});var I=0,R=[],j={},N={},F=!1,B=0,L=new s.Parser({onopentag:function(e,n){if(F)return void B++;var a=new _(e,n);R.push(a);var s,u=!1,l=!!a.text;i(P,e)&&(s=P[e](e,n),a.attribs=n=s.attribs,void 0!==s.text&&(a.innerText=s.text),e!==s.tagName&&(a.name=e=s.tagName,N[I]=s.tagName)),T&&(s=T(e,n),a.attribs=n=s.attribs,e!==s.tagName&&(a.name=e=s.tagName,N[I]=s.tagName)),t.allowedTags&&-1===t.allowedTags.indexOf(e)&&(u=!0,-1!==O.indexOf(e)&&(F=!0,B=1),j[I]=!0),I++,u||(C+="<"+e,(!A||i(A,e)||A["*"])&&r(n,function(n,s){if(!g.test(s))return void delete a.attribs[s];var u,l=!1;if(!A||i(A,e)&&-1!==A[e].indexOf(s)||A["*"]&&-1!==A["*"].indexOf(s)||i(D,e)&&D[e].test(s)||D["*"]&&D["*"].test(s))l=!0;else if(A&&A[e]){var c=!0,p=!1,f=void 0;try{for(var y,_=A[e][Symbol.iterator]();!(c=(y=_.next()).done);c=!0){var E=y.value;if(h(E)&&E.name&&E.name===s){l=!0;var O="";if(!0===E.multiple){var T=n.split(" "),P=!0,I=!1,R=void 0;try{for(var j,N=T[Symbol.iterator]();!(P=(j=N.next()).done);P=!0){var F=j.value;-1!==E.values.indexOf(F)&&(""===O?O=F:O+=" "+F)}}catch(e){I=!0,R=e}finally{try{!P&&N.return&&N.return()}finally{if(I)throw R}}}else E.values.indexOf(n)>=0&&(O=n);n=O}}}catch(e){p=!0,f=e}finally{try{!c&&_.return&&_.return()}finally{if(p)throw f}}}if(l){if(-1!==t.allowedSchemesAppliedToAttributes.indexOf(s)&&x(e,n))return void delete a.attribs[s];if("iframe"===e&&"src"===s){if("//"===n.substring(0,2)){n="https:".concat(n)}try{if(u=v.parse(n),t.allowedIframeHostnames){if(!t.allowedIframeHostnames.find(function(e){return e===u.hostname}))return void delete a.attribs[s]}}catch(e){return void delete a.attribs[s]}}if("srcset"===s)try{if(u=d.parse(n),r(u,function(e){x("srcset",e.url)&&(e.evil=!0)}),u=o(u,function(e){return!e.evil}),!u.length)return void delete a.attribs[s];n=d.stringify(o(u,function(e){return!e.evil})),a.attribs[s]=n}catch(e){return void delete a.attribs[s]}if("class"===s&&(n=S(n,M[e]),!n.length))return void delete a.attribs[s];if("style"===s)try{if(n=k(w(m.parse(e+" {"+n+"}"),t.allowedStyles)),0===n.length)return void delete a.attribs[s]}catch(e){return void delete a.attribs[s]}C+=" "+s,n.length&&(C+='="'+b(n)+'"')}else delete a.attribs[s]}),-1!==t.selfClosing.indexOf(e)?C+=" />":(C+=">",!a.innerText||l||t.textFilter||(C+=a.innerText)))},ontext:function(e){if(!F){var n,r=R[R.length-1];if(r&&(n=r.tag,e=void 0!==r.innerText?r.innerText:e),"script"===n||"style"===n)C+=e;else{var i=b(e);t.textFilter?C+=t.textFilter(i):C+=i}if(R.length){R[R.length-1].text+=e}}},onclosetag:function(e){if(F){if(--B)return;F=!1}var n=R.pop();if(n){if(F=!1,I--,j[I])return delete j[I],void n.updateParentNodeText();if(N[I]&&(e=N[I],deleteLine truncated
|
||||
//# sourceMappingURL=swagger-ui-bundle.js.map
|
||||
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:///swagger-ui-bundle.js","webpack:///webpack/bootstrap cb7bb5ab2187b0d4f5b6","webpack:///./~/react/react.js","webpack:///./~/prop-types/index.js","webpack:///./~/babel-runtime/helpers/classCallCheck.js","webpack:///./~/babel-runtime/helpers/createClass.js","webpack:///./~/babel-runtime/core-js/object/get-prototype-of.js","webpack:///./~/babel-runtime/helpers/inherits.js","webpack:///./~/babel-runtime/helpers/possibleConstructorReturn.js","webpack:///./~/immutable/dist/immutable.js","webpack:///./~/fbjs/lib/invariant.js","webpack:///./src/core/utils.js","webpack:///./~/fbjs/lib/warning.js","webpack:///./~/react-dom/lib/reactProdInvariant.js","webpack:///./~/react-immutable-proptypes/dist/ImmutablePropTypes.js","webpack:///./~/object-assign/index.js","webpack:///./~/react-dom/lib/ReactDOMComponentTree.js","webpack:///./~/core-js/library/modules/_core.js","webpack:///(webpack)/buildin/global.js","webpack:///./~/js-yaml/lib/js-yaml/type.js","webpack:///./~/babel-runtime/helpers/slicedToArray.js","webpack:///./~/core-js/modules/_wks.js","webpack:///./~/babel-runtime/helpers/extends.js","webpack:///./~/core-js/library/modules/_wks.js","webpack:///./~/lodash/isArray.js","webpack:///./~/core-js/library/modules/_export.js","webpack:///./~/core-js/library/modules/_global.js","webpack:///./~/fbjs/lib/ExecutionEnvironment.js","webpack:///./~/remarkable/lib/common/utils.js","webpack:///./~/babel-runtime/core-js/object/assign.js","webpack:///./~/babel-runtime/helpers/defineProperty.js","webpack:///./~/core-js/library/modules/_is-object.js","webpack:///./~/core-js/modules/_export.js","webpack:///./~/core-js/modules/_string-html.js","webpack:///./~/core-js/modules/_global.js","webpack:///./~/fbjs/lib/emptyFunction.js","webpack:///./~/process/browser.js","webpack:///./src/core/plugins/oas3/helpers.js","webpack:///./src/core/window.js","webpack:///./~/babel-runtime/core-js/json/stringify.js","webpack:///./~/core-js/library/modules/_an-object.js","webpack:///./~/lodash/_root.js","webpack:///./~/lodash/isObject.js","webpack:///./~/react-dom/lib/ReactInstrumentation.js","webpack:///./~/babel-runtime/core-js/object/keys.js","webpack:///./~/buffer/index.js","webpack:///./~/core-js/library/modules/_object-dp.js","webpack:///./~/inherits/inherits_browser.js","webpack:///./~/react-dom/lib/ReactUpdates.js","webpack:///./~/yaml-js/lib/errors.js","webpack:///./~/babel-runtime/helpers/typeof.js","webpack:///./~/core-js/library/modules/_descriptors.js","webpack:///./~/inline-style-prefixer/utils/getPrefixedValue.js","webpack:///./~/lodash/isObjectLike.js","webpack:///./~/react-dom/lib/SyntheticEvent.js","webpack:///./~/react/lib/ReactCurrentOwner.js","webpack:///./~/core-js/library/modules/_ctx.js","webpack:///./~/core-js/library/modules/_fails.js","webpack:///./~/core-js/library/modules/_has.js","webpack:///./~/core-js/library/modules/_hide.js","webpack:///./~/core-js/modules/_defined.js","webpack:///./~/es5-ext/object/valid-callable.js","webpack:///./~/reselect/lib/index.js","webpack:///./~/yaml-js/lib/util.js","webpack:///./~/core-js/modules/_an-object.js","webpack:///./~/core-js/modules/_core.js","webpack:///./~/core-js/modules/_hide.js","webpack:///./~/es5-ext/number/to-pos-integer.js","webpack:///./~/lodash/_baseGetTag.js","webpack:///./~/lodash/_getNative.js","webpack:///./~/lodash/keys.js","webpack:///./~/react-dom/lib/PooledClass.js","webpack:///./~/readable-stream/lib/_stream_duplex.js","webpack:///./~/babel-runtime/helpers/toConsumableArray.js","webpack:///./~/commonmark/lib/common.js","webpack:///./~/core-js/library/modules/_iterators.js","webpack:///./~/core-js/library/modules/_to-iobject.js","webpack:///./~/core-js/library/modules/_to-object.js","webpack:///./~/core-js/modules/_is-object.js","webpack:///./~/core-js/modules/_redefine.js","webpack:///./~/es5-ext/object/is-value.js","webpack:///./~/js-yaml/lib/js-yaml/common.js","webpack:///./~/js-yaml/lib/js-yaml/schema.js","webpack:///./~/lodash/_Symbol.js","webpack:///./~/lodash/_castPath.js","webpack:///./~/lodash/_copyObject.js","webpack:///./~/lodash/_toKey.js","webpack:///./~/lodash/isArrayLike.js","webpack:///./~/lodash/toString.js","webpack:///./~/react-dom/lib/DOMLazyTree.js","webpack:///./~/react-dom/lib/DOMProperty.js","webpack:///./~/react-dom/lib/ReactReconciler.js","webpack:///./~/react-markdown/~/commonmark/lib/common.js","webpack:///./~/react/lib/React.js","webpack:///./~/react/lib/ReactElement.js","webpack:///(webpack)/buildin/module.js","webpack:///./~/yaml-js/lib/nodes.js","webpack:///./~/babel-runtime/core-js/get-iterator.js","webpack:///./~/babel-runtime/helpers/objectWithoutProperties.js","webpack:///./~/core-js/library/modules/_a-function.js","webpack:///./~/core-js/library/modules/_cof.js","webpack:///./~/core-js/library/modules/_object-keys.js","webpack:///./~/core-js/library/modules/_property-desc.js","webpack:///./~/core-js/library/modules/_set-to-string-tag.js","webpacLine truncated
|
||||
@@ -1,13 +0,0 @@
|
||||
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.SwaggerUIStandalonePreset=e():t.SwaggerUIStandalonePreset=e()}(this,function(){return function(t){function e(r){if(n[r])return n[r].exports;var i=n[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,e),i.l=!0,i.exports}var n={};return e.m=t,e.c=n,e.i=function(t){return t},e.d=function(t,n,r){e.o(t,n)||Object.defineProperty(t,n,{configurable:!1,enumerable:!0,get:r})},e.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,"a",n),n},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="/dist",e(e.s=537)}([function(t,e,n){"use strict";function r(t){var e={};return null!==t&&Object.keys(t).forEach(function(n){t[n].forEach(function(t){e[String(t)]=n})}),e}function i(t,e){if(e=e||{},Object.keys(e).forEach(function(e){if(-1===s.indexOf(e))throw new o('Unknown option "'+e+'" is met in definition of "'+t+'" YAML type.')}),this.tag=t,this.kind=e.kind||null,this.resolve=e.resolve||function(){return!0},this.construct=e.construct||function(t){return t},this.instanceOf=e.instanceOf||null,this.predicate=e.predicate||null,this.represent=e.represent||null,this.defaultStyle=e.defaultStyle||null,this.styleAliases=r(e.styleAliases||null),-1===a.indexOf(this.kind))throw new o('Unknown kind "'+this.kind+'" is specified for "'+t+'" YAML type.')}var o=n(47),s=["kind","resolve","construct","instanceOf","predicate","represent","defaultStyle","styleAliases"],a=["scalar","sequence","mapping"];t.exports=i},function(t,e,n){var r=n(153)("wks"),i=n(108),o=n(5).Symbol,s="function"==typeof o;(t.exports=function(t){return r[t]||(r[t]=s&&o[t]||(s?o:i)("Symbol."+t))}).store=r},function(t,e){var n=t.exports={version:"2.5.4"};"number"==typeof __e&&(__e=n)},function(t,e,n){var r=n(5),i=n(18),o=n(19),s=n(30),a=n(60),u=function(t,e,n){var c,l,h,f,p=t&u.F,d=t&u.G,m=t&u.S,v=t&u.P,y=t&u.B,g=d?r:m?r[e]||(r[e]={}):(r[e]||{}).prototype,x=d?i:i[e]||(i[e]={}),b=x.prototype||(x.prototype={});d&&(n=e);for(c in n)l=!p&&g&&void 0!==g[c],h=(l?g:n)[c],f=y&&l?a(h,r):v&&"function"==typeof h?a(Function.call,h):h,g&&s(g,c,h,t&u.U),x[c]!=h&&o(x,c,f),v&&b[c]!=h&&(b[c]=h)};r.core=i,u.F=1,u.G=2,u.S=4,u.P=8,u.B=16,u.W=32,u.U=64,u.R=128,t.exports=u},function(t,e,n){var r=n(3),i=n(42),o=n(10),s=/"/g,a=function(t,e,n,r){var i=String(o(t)),a="<"+e;return""!==n&&(a+=" "+n+'="'+String(r).replace(s,""")+'"'),a+">"+i+"</"+e+">"};t.exports=function(t,e){var n={};n[t]=e(a),r(r.P+r.F*i(function(){var e=""[t]('"');return e!==e.toLowerCase()||e.split('"').length>3}),"String",n)}},function(t,e){var n=t.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},function(t,e,n){var r=n(94)("wks"),i=n(58),o=n(9).Symbol,s="function"==typeof o;(t.exports=function(t){return r[t]||(r[t]=s&&o[t]||(s?o:i)("Symbol."+t))}).store=r},function(t,e,n){var r=n(177),i="object"==typeof self&&self&&self.Object===Object&&self,o=r||i||Function("return this")();t.exports=o},function(t,e){var n=Array.isArray;t.exports=n},function(t,e){var n=t.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},function(t,e){t.exports=function(t){if(void 0==t)throw TypeError("Can't call method on "+t);return t}},function(t,e,n){"use strict";t.exports=function(t){if("function"!=typeof t)throw new TypeError(t+" is not a function");return t}},function(t,e){var n;n=function(){return this}();try{n=n||Function("return this")()||(0,eval)("this")}catch(t){"object"==typeof window&&(n=window)}t.exports=n},function(t,e,n){t.exports=!n(25)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(t,e,n){var r=n(9),i=n(2),o=n(133),s=n(26),a=n(15),u=function(t,e,n){var c,l,h,f=t&u.F,p=t&u.G,d=t&u.S,m=t&u.P,v=t&u.B,y=t&u.W,g=p?i:i[e]||(i[e]={}),x=g.prototype,b=p?r:d?r[e]:(r[e]||{}).prototype;p&&(n=e);for(c in n)(l=!f&&b&&void 0!==b[c])&&a(g,c)||(h=l?b[c]:n[c],g[c]=p&&"function"!=typeof b[c]?n[c]:v&&l?o(h,r):y&&b[c]==h?function(t){var e=function(e,n,r){if(this instanceof t){switch(arguments.length){case 0:return new t;case 1:return new t(e);case 2:return new t(e,n)}return new t(e,n,r)}return t.apply(this,arguments)};return e.prototype=t.prototype,e}(h):m&&"function"==typeof h?o(Function.call,h):h,m&&((g.virtual||(g.virtual={}))[c]=h,t&u.R&&x&&!x[c]&&s(x,c,h)))};u.F=1,u.G=2,u.S=4,u.P=8,u.B=16,u.W=32,u.U=64,u.R=128,t.exports=u},function(t,e){var n={}.hasOwnProperty;t.exports=function(t,e){return n.call(t,e)}},function(t,e,n){var r=n(24),i=n(135),o=n(96),s=Object.defineProperty;e.f=n(13)?Object.defineProperty:function(t,e,n){if(r(t),e=o(e,!0),r(n),i)try{return s(t,e,n)}catch(t){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");reLine truncated
|
||||
object-assign
|
||||
(c) Sindre Sorhus
|
||||
@license MIT
|
||||
*/
|
||||
var i=Object.getOwnPropertySymbols,o=Object.prototype.hasOwnProperty,s=Object.prototype.propertyIsEnumerable;t.exports=function(){try{if(!Object.assign)return!1;var t=new String("abc");if(t[5]="de","5"===Object.getOwnPropertyNames(t)[0])return!1;for(var e={},n=0;n<10;n++)e["_"+String.fromCharCode(n)]=n;if("0123456789"!==Object.getOwnPropertyNames(e).map(function(t){return e[t]}).join(""))return!1;var r={};return"abcdefghijklmnopqrst".split("").forEach(function(t){r[t]=t}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},r)).join("")}catch(t){return!1}}()?Object.assign:function(t,e){for(var n,a,u=r(t),c=1;c<arguments.length;c++){n=Object(arguments[c]);for(var l in n)o.call(n,l)&&(u[l]=n[l]);if(i){a=i(n);for(var h=0;h<a.length;h++)s.call(n,a[h])&&(u[a[h]]=n[a[h]])}}return u}},function(t,e,n){"use strict";(function(t){function r(){return o.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function i(t,e){if(r()<e)throw new RangeError("Invalid typed array length");return o.TYPED_ARRAY_SUPPORT?(t=new Uint8Array(e),t.__proto__=o.prototype):(null===t&&(t=new o(e)),t.length=e),t}function o(t,e,n){if(!(o.TYPED_ARRAY_SUPPORT||this instanceof o))return new o(t,e,n);if("number"==typeof t){if("string"==typeof e)throw new Error("If encoding is specified then the first argument must be a string");return c(this,t)}return s(this,t,e,n)}function s(t,e,n,r){if("number"==typeof e)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer?f(t,e,n,r):"string"==typeof e?l(t,e,n):p(t,e)}function a(t){if("number"!=typeof t)throw new TypeError('"size" argument must be a number');if(t<0)throw new RangeError('"size" argument must not be negative')}function u(t,e,n,r){return a(e),e<=0?i(t,e):void 0!==n?"string"==typeof r?i(t,e).fill(n,r):i(t,e).fill(n):i(t,e)}function c(t,e){if(a(e),t=i(t,e<0?0:0|d(e)),!o.TYPED_ARRAY_SUPPORT)for(var n=0;n<e;++n)t[n]=0;return t}function l(t,e,n){if("string"==typeof n&&""!==n||(n="utf8"),!o.isEncoding(n))throw new TypeError('"encoding" must be a valid string encoding');var r=0|v(e,n);t=i(t,r);var s=t.write(e,n);return s!==r&&(t=t.slice(0,s)),t}function h(t,e){var n=e.length<0?0:0|d(e.length);t=i(t,n);for(var r=0;r<n;r+=1)t[r]=255&e[r];return t}function f(t,e,n,r){if(e.byteLength,n<0||e.byteLength<n)throw new RangeError("'offset' is out of bounds");if(e.byteLength<n+(r||0))throw new RangeError("'length' is out of bounds");return e=void 0===n&&void 0===r?new Uint8Array(e):void 0===r?new Uint8Array(e,n):new Uint8Array(e,n,r),o.TYPED_ARRAY_SUPPORT?(t=e,t.__proto__=o.prototype):t=h(t,e),t}function p(t,e){if(o.isBuffer(e)){var n=0|d(e.length);return t=i(t,n),0===t.length?t:(e.copy(t,0,0,n),t)}if(e){if("undefined"!=typeof ArrayBuffer&&e.buffer instanceof ArrayBuffer||"length"in e)return"number"!=typeof e.length||H(e.length)?i(t,0):h(t,e);if("Buffer"===e.type&&Z(e.data))return h(t,e.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}function d(t){if(t>=r())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r().toString(16)+" bytes");return 0|t}function m(t){return+t!=t&&(t=0),o.alloc(+t)}function v(t,e){if(o.isBuffer(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var n=t.length;if(0===n)return 0;for(var r=!1;;)switch(e){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return q(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return Y(t).length;default:if(r)return q(t).length;e=(""+e).toLowerCase(),r=!0}}function y(t,e,n){var r=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if(n>>>=0,e>>>=0,n<=e)return"";for(t||(t="utf8");;)switch(t){case"hex":return O(this,e,n);case"utf8":case"utf-8":return k(this,e,n);case"ascii":return T(this,e,n);case"latin1":case"binary":return I(this,e,n);case"base64":return C(this,e,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return M(this,e,n);default:if(r)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),r=!0}}function g(t,e,n){var r=t[e];t[e]=t[n],t[n]=r}function x(t,e,n,r,i){if(0===t.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=i?0:t.length-1),n<0&&(n=t.length+n),n>=t.length){if(i)return-1;n=t.length-1}else if(n<0){if(!i)return-1;n=0}if("string"==typeof e&&(e=o.from(e,r)),o.isBuffer(e))return 0===e.length?-1:b(t,e,n,r,i);if("number"==typeof e)return e&=255,o.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,n):Uint8Array.prototype.lastIndexOf.call(t,e,n):b(t,[e],n,r,i);throw new TypeError("val must be string, number or Buffer")}function b(t,e,n,r,i){function o(t,e){returnLine truncated
|
||||
* The buffer module from node.js, for the browser.
|
||||
*
|
||||
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
|
||||
* @license MIT
|
||||
*/
|
||||
var G=n(223),$=n(357),Z=n(168);e.Buffer=o,e.SlowBuffer=m,e.INSPECT_MAX_BYTES=50,o.TYPED_ARRAY_SUPPORT=void 0!==t.TYPED_ARRAY_SUPPORT?t.TYPED_ARRAY_SUPPORT:function(){try{var t=new Uint8Array(1);return t.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===t.foo()&&"function"==typeof t.subarray&&0===t.subarray(1,1).byteLength}catch(t){return!1}}(),e.kMaxLength=r(),o.poolSize=8192,o._augment=function(t){return t.__proto__=o.prototype,t},o.from=function(t,e,n){return s(null,t,e,n)},o.TYPED_ARRAY_SUPPORT&&(o.prototype.__proto__=Uint8Array.prototype,o.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&o[Symbol.species]===o&&Object.defineProperty(o,Symbol.species,{value:null,configurable:!0})),o.alloc=function(t,e,n){return u(null,t,e,n)},o.allocUnsafe=function(t){return c(null,t)},o.allocUnsafeSlow=function(t){return c(null,t)},o.isBuffer=function(t){return!(null==t||!t._isBuffer)},o.compare=function(t,e){if(!o.isBuffer(t)||!o.isBuffer(e))throw new TypeError("Arguments must be Buffers");if(t===e)return 0;for(var n=t.length,r=e.length,i=0,s=Math.min(n,r);i<s;++i)if(t[i]!==e[i]){n=t[i],r=e[i];break}return n<r?-1:r<n?1:0},o.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},o.concat=function(t,e){if(!Z(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return o.alloc(0);var n;if(void 0===e)for(e=0,n=0;n<t.length;++n)e+=t[n].length;var r=o.allocUnsafe(e),i=0;for(n=0;n<t.length;++n){var s=t[n];if(!o.isBuffer(s))throw new TypeError('"list" argument must be an Array of Buffers');s.copy(r,i),i+=s.length}return r},o.byteLength=v,o.prototype._isBuffer=!0,o.prototype.swap16=function(){var t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var e=0;e<t;e+=2)g(this,e,e+1);return this},o.prototype.swap32=function(){var t=this.length;if(t%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var e=0;e<t;e+=4)g(this,e,e+3),g(this,e+1,e+2);return this},o.prototype.swap64=function(){var t=this.length;if(t%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var e=0;e<t;e+=8)g(this,e,e+7),g(this,e+1,e+6),g(this,e+2,e+5),g(this,e+3,e+4);return this},o.prototype.toString=function(){var t=0|this.length;return 0===t?"":0===arguments.length?k(this,0,t):y.apply(this,arguments)},o.prototype.equals=function(t){if(!o.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===o.compare(this,t)},o.prototype.inspect=function(){var t="",n=e.INSPECT_MAX_BYTES;return this.length>0&&(t=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(t+=" ... ")),"<Buffer "+t+">"},o.prototype.compare=function(t,e,n,r,i){if(!o.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===n&&(n=t?t.length:0),void 0===r&&(r=0),void 0===i&&(i=this.length),e<0||n>t.length||r<0||i>this.length)throw new RangeError("out of range index");if(r>=i&&e>=n)return 0;if(r>=i)return-1;if(e>=n)return 1;if(e>>>=0,n>>>=0,r>>>=0,i>>>=0,this===t)return 0;for(var s=i-r,a=n-e,u=Math.min(s,a),c=this.slice(r,i),l=t.slice(e,n),h=0;h<u;++h)if(c[h]!==l[h]){s=c[h],a=l[h];break}return s<a?-1:a<s?1:0},o.prototype.includes=function(t,e,n){return-1!==this.indexOf(t,e,n)},o.prototype.indexOf=function(t,e,n){return x(this,t,e,n,!0)},o.prototype.lastIndexOf=function(t,e,n){return x(this,t,e,n,!1)},o.prototype.write=function(t,e,n,r){if(void 0===e)r="utf8",n=this.length,e=0;else if(void 0===n&&"string"==typeof e)r=e,n=this.length,e=0;else{if(!isFinite(e))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");e|=0,isFinite(n)?(n|=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}var i=this.length-e;if((void 0===n||n>i)&&(n=i),t.length>0&&(n<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var o=!1;;)switch(r){case"hex":return D(this,t,e,n);case"utf8":case"utf-8":return E(this,t,e,n);case"ascii":return w(this,t,e,n);case"latin1":case"binary":return _(this,t,e,n);case"base64":return S(this,t,e,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,t,e,n);default:if(o)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),o=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Q=4096;o.prototype.slice=function(t,e){var n=this.length;t=~~t,e=void 0===e?n:~~e,t<0?(t+=n)<0&&(t=0):t>n&&(t=n),e<0?(e+=n)<0&&(e=0):e>n&&(e=n),e<t&&(e=t);var r;if(o.TYPED_ARRAY_SUPPORT)r=this.subarray(t,e),r.__proto__=o.prototype;else{var i=e-t;r=new o(i,void 0);for(var s=0;s<i;++s)r[s]=this[s+t]}return r},o.prototype.readUIntLE=function(t,e,n){t|=0,e|=0,n||B(t,e,this.length);for(var r=this[t],i=1,o=0;++o<e&&(i*=256);)r+=this[t+o]*i;return r},o.prototype.readUIntBE=function(t,e,n){Line truncated
|
||||
//# sourceMappingURL=swagger-ui-standalone-preset.js.map
|
||||
Loaded 100 of 121 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user