diff --git a/.version b/.version index 9084fa2..227cea2 100644 --- a/.version +++ b/.version @@ -1 +1 @@ -1.1.0 +2.0.0 diff --git a/Gopkg.lock b/Gopkg.lock index f4ac2ee..4e11687 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -2,12 +2,12 @@ [[projects]] - digest = "1:e92f5581902c345eb4ceffdcd4a854fb8f73cf436d47d837d1ec98ef1fe0a214" - name = "github.com/StackExchange/wmi" + 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" @@ -18,12 +18,12 @@ version = "v9" [[projects]] - digest = "1:652880afc6b57ce0a67173f552cb35ccda816493a1da6ca20e5074a66bcd083f" - name = "github.com/buaazp/fasthttprouter" + digest = "1:0f98f59e9a2f4070d66f0c9c39561f68fcd1dc837b22a852d28d0003aebd1b1e" + name = "github.com/boltdb/bolt" packages = ["."] pruneopts = "UT" - revision = "ade4e2031af3aed7fffd241084aad80a58faf421" - version = "v0.1.1" + revision = "2f1ce7a837dcb8da3ec595b1dac9d0632f0f99e8" + version = "v1.3.1" [[projects]] digest = "1:c1100fc71e23b6a32b2c68a5202a848fd13811d5a10b12edb8019c3667d1cd9a" @@ -42,75 +42,46 @@ 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:d02b94ed7089fc72fcd2e89c89df858c843470fe36788df39bf45e074293165e" - name = "github.com/go-pg/pg" - packages = [ - ".", - "internal", - "internal/iszero", - "internal/parser", - "internal/pool", - "internal/struct_filter", - "internal/tag", - "orm", - "types", - ] - pruneopts = "UT" - revision = "11cb265cd96c769490bea4cdc3634ea2049197f6" - version = "v8.0.4" - -[[projects]] - digest = "1:489a99067cd08971bd9c1ee0055119ba8febc1429f9200ab0bec68d35e8c4833" + 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 = "b5d812f8a3706043e23a9cd5babf2e5423744d30" - version = "v1.3.1" + revision = "6c65a5562fc06764971b7c5d05c76c75e84bdbf7" + version = "v1.3.2" [[projects]] - digest = "1:324591cd9122f94cc39a87bd44ec71153672c239e2cff5743bfad96b60be3749" + digest = "1:6b7e9b1e2f944a0c84f29943f705954d2d8cfbf6477c37a10d0c80acdbc2445f" name = "github.com/googollee/go-engine.io" packages = [ ".", - "message", - "parser", - "polling", + "base", + "packet", + "payload", "transport", - "websocket", + "transport/polling", + "transport/websocket", ] pruneopts = "UT" - revision = "e2f255711dcb2ea41e42c6d9d98c172d7edf6509" + revision = "cc5b8c07e074e97f6bc6f4c6dbc03cf06267e6e0" + version = "v1.4.1" [[projects]] - digest = "1:3eb026ba34d6dd12b45bb6abd63b4e917ebca8d8f3022a139c0881d900ad1bee" + digest = "1:25fa43cb2f30c0ab54aaabf05167c56c7e385635b3651015c5726ecb737a905e" name = "github.com/googollee/go-socket.io" - packages = ["."] + packages = [ + ".", + "parser", + ] pruneopts = "UT" - revision = "c8aeb1ed9b49d7de8fef8662efb18f1d289c5f2e" + revision = "96da97a7c8f269421388fbb0dca12aa3c0699088" + version = "v1.4.1" [[projects]] digest = "1:7b5c6e2eeaa9ae5907c391a91c132abfd5c9e8a784a341b5625e750c67e6825d" @@ -121,16 +92,36 @@ version = "v1.4.0" [[projects]] - digest = "1:d99022a1f51cb2223bf227388c8d8260c8e593dac415584964fe6865bfcf7525" - name = "github.com/grpc-ecosystem/grpc-gateway" - packages = [ - "internal", - "runtime", - "utilities", - ] + digest = "1:cf6b61e1b4c26b0c7526cee4a0cee6d8302b17798af4b2a56a90eedac0aef11a" + name = "github.com/hashicorp/go-hclog" + packages = ["."] pruneopts = "UT" - revision = "15c7b2ea9d896c07d9b28eca57050b1ee0aea4d6" - version = "v1.8.6" + revision = "5ccdce08c75b6c7b37af61159f13f6a4f5e2e928" + version = "v0.9.2" + +[[projects]] + digest = "1:6e9806a06d00f4d1f90806d7b5cfb11e35dca76503390ca6e704b05ea7051bff" + name = "github.com/hashicorp/go-immutable-radix" + packages = ["."] + pruneopts = "UT" + revision = "7dd1121b595e4e1bd6dd5caa78e0f5c454740379" + version = "v1.1.0" + +[[projects]] + digest = "1:5d8539af558ca2ea960a4c11afb12c75ae9e9dca3560f1103318aaa2030e37e2" + name = "github.com/hashicorp/go-msgpack" + packages = ["codec"] + pruneopts = "UT" + revision = "ad60660ecf9c5a1eae0ca32182ed72bab5807961" + version = "v0.5.5" + +[[projects]] + digest = "1:7fae9ec96d10b2afce0da23c378c8b3389319b7f92fa092f2621bba3078cfb4b" + name = "github.com/hashicorp/golang-lru" + packages = ["simplelru"] + pruneopts = "UT" + revision = "7f827b33c0f158ec5dfbba01bb0b14a4541fd81d" + version = "v0.5.3" [[projects]] digest = "1:c0d19ab64b32ce9fe5cf4ddceba78d5bc9807f0016db6b1183599da3dcc24d10" @@ -151,6 +142,22 @@ revision = "8cb6e5b959231cc1119e43259c4a608f9c51a241" version = "v1.0.0" +[[projects]] + digest = "1:27a5032b785c980b947d6dedb6061647f557fadc3141ce79569f89cef4932acf" + name = "github.com/hashicorp/raft" + packages = ["."] + pruneopts = "UT" + revision = "ff523e1c1515a5b33cc3153a34c984093fed06bb" + version = "v1.1.1" + +[[projects]] + branch = "master" + digest = "1:82a7ef5075b82f6eed79af9e6d5196036e2af200016bc565d627c579066ab010" + name = "github.com/hashicorp/raft-boltdb" + packages = ["."] + pruneopts = "UT" + revision = "ef2e128ed477fd15f4a9a7092e4a9a8408008fb5" + [[projects]] branch = "master" digest = "1:7edb99b124d77ae909910e2ba563fbe652e9596f5798bd10f67fd66ba0fa9c82" @@ -185,25 +192,21 @@ revision = "5959fcea049facd9441fff9de976191accd3cf9f" [[projects]] - digest = "1:0bdf657bbf0ecebb68dd69296c3344eed6136044a46e608e73a3ccc9d1f2b967" + digest = "1:fd6ba35c1332fa3ad5be6f4fa1206adba26c184e79f32310a0c50b6811e0e530" name = "github.com/integration-system/isp-lib" packages = [ "backend", - "bootstrap", "config", "config/schema", - "database", "logger", - "metric", "proto/stubs", - "socket", "streaming", "structure", "utils", ] pruneopts = "UT" - revision = "b9d4753188c313e0d0d87fcfaee878dc392334df" - version = "v1.2.0" + revision = "d2cc77b8fb8648ae7f8efdf1d1b834e8e57b56d7" + version = "v1.5.2" [[projects]] branch = "master" @@ -214,43 +217,15 @@ revision = "5475a8b08e62e41fa886641861ac225e7f91e4e5" [[projects]] - branch = "master" - digest = "1:fd97437fbb6b7dce04132cf06775bd258cce305c44add58eb55ca86c6c325160" - name = "github.com/jinzhu/inflection" - packages = ["."] - pruneopts = "UT" - revision = "04140366298a54a039076d798123ffa108fff46c" - -[[projects]] - digest = "1:e4f630893d2bbf8c268eba14e7cc92ef8844ee259a45e21ea77cf7656544cb7e" + digest = "1:ac7f1061abc812a5d0de6df7e3f477cef942aef503848f436da0f0eb2603bfbf" name = "github.com/json-iterator/go" packages = [ ".", "extra", ] pruneopts = "UT" - revision = "0ff49de124c6f76f8494e194af75bde0f1a49a29" - version = "v1.1.6" - -[[projects]] - digest = "1:aaa8e0e7e35d92e21daed3f241832cee73d15ca1cd3302ba3843159a959a7eac" - name = "github.com/klauspost/compress" - packages = [ - "flate", - "gzip", - "zlib", - ] - pruneopts = "UT" - revision = "b4b6d9e7f099f14b3a4a08f0664986cd4c85ebd6" - version = "v1.5.0" - -[[projects]] - digest = "1:923c4d7194b42e054b2eb8a6c62824ac55e23ececc1c7e48d4da69c971c55954" - name = "github.com/klauspost/cpuid" - packages = ["."] - pruneopts = "UT" - revision = "05a8198c0f5a27739aec358908d7e12c64ce6eb7" - version = "v1.2.1" + revision = "27518f6661eba504be5a7a9a9f6d9460d892ade3" + version = "v1.1.7" [[projects]] digest = "1:31e761d97c76151dde79e9d28964a812c46efc5baee4085b86f68f0c654450de" @@ -260,18 +235,6 @@ revision = "f55edac94c9bbba5d6182a4be46d86a2c9b5b50e" version = "v1.0.2" -[[projects]] - digest = "1:bdd53b87de8185da386bae179c84d4848854c6870bacacf6a154fe63e2e750f7" - name = "github.com/lib/pq" - packages = [ - ".", - "oid", - "scram", - ] - pruneopts = "UT" - revision = "bc6a3c0594130b1e34005880bc600b6d3f49fa7f" - version = "v1.1.1" - [[projects]] digest = "1:5a0ef768465592efca0412f7e838cdc0826712f8447e70e6ccc52eb441e9ab13" name = "github.com/magiconair/properties" @@ -281,20 +244,20 @@ version = "v1.8.1" [[projects]] - digest = "1:2fa7b0155cd54479a755c629de26f888a918e13f8857a2c442205d825368e084" + digest = "1:7c084e0e780596dd2a7e20d25803909a9a43689c153de953520dfbc0b0e51166" name = "github.com/mattn/go-colorable" packages = ["."] pruneopts = "UT" - revision = "3a70a971f94a22f2fa562ffcc7a0eb45f5daf045" - version = "v0.1.1" + revision = "8029fb3788e5a4a9c00e415f586a6d033f5d38b3" + version = "v0.1.2" [[projects]] - digest = "1:e150b5fafbd7607e2d638e4e5cf43aa4100124e5593385147b0a74e2733d8b0d" + digest = "1:9b90c7639a41697f3d4ad12d7d67dfacc9a7a4a6e0bbfae4fc72d0da57c28871" name = "github.com/mattn/go-isatty" packages = ["."] pruneopts = "UT" - revision = "c2a7a6ca930a4cd0bc33a3f298eb71960732a3a7" - version = "v0.0.7" + revision = "1311e847b0cb909da63b5fecfb5370aa66236465" + version = "v0.0.8" [[projects]] branch = "master" @@ -353,39 +316,12 @@ version = "v0.8.1" [[projects]] - digest = "1:7d99649602f68b73ade640ca6975ccc38735f329e159c6a507b63f00213678c0" - name = "github.com/pressly/goose" - packages = ["."] - pruneopts = "UT" - revision = "e4b98955473e91a12fc7d8816c28d06376d1d92c" - version = "v2.6.0" - -[[projects]] - branch = "master" - digest = "1:d38f81081a389f1466ec98192cf9115a82158854d6f01e1c23e2e7554b97db71" - name = "github.com/rcrowley/go-metrics" - packages = ["."] - pruneopts = "UT" - revision = "3113b8401b8a98917cde58f8bbd42a1b1c03b1fd" - -[[projects]] - digest = "1:bfc1b9ae0c8c925613f67faff48d1330cdfc48e70073b3bd0645290373aa9165" - name = "github.com/shirou/gopsutil" - packages = [ - "cpu", - "internal/common", - ] - pruneopts = "UT" - revision = "fa9845945e5b5c6ffb19b436586ff702a30417c5" - version = "v2.19.04" - -[[projects]] - digest = "1:fd61cf4ae1953d55df708acb6b91492d538f49c305b364a014049914495db426" + digest = "1:04457f9f6f3ffc5fea48e71d62f2ca256637dee0a04d710288e27e05c8b41976" name = "github.com/sirupsen/logrus" packages = ["."] pruneopts = "UT" - revision = "8bdbc7bcc01dcbb8ec23dc8a28e332258d25251f" - version = "v1.4.1" + revision = "839c75faf7f98a33d445d181f3018b5c3409a45e" + version = "v1.4.2" [[projects]] digest = "1:bb495ec276ab82d3dd08504bbc0594a65de8c3b22c6f2aaa92d05b73fbf3a82e" @@ -423,12 +359,12 @@ version = "v1.0.3" [[projects]] - digest = "1:1b773526998f3dbde3a51a4a5881680c4d237d3600f570d900f97ac93c7ba0a8" + digest = "1:11118bd196646c6515fea3d6c43f66162833c6ae4939bfb229b9956d91c6cf17" name = "github.com/spf13/viper" packages = ["."] pruneopts = "UT" - revision = "9e56dacc08fbbf8c9ee2dbc717553c758ce42bc9" - version = "v1.3.2" + revision = "b5bf975e5823809fb22c7644d008757f78a4259e" + version = "v1.4.0" [[projects]] branch = "master" @@ -438,26 +374,6 @@ pruneopts = "UT" revision = "a83968bda2d37294a3541b7d2207fb6f5a3559a3" -[[projects]] - digest = "1:c468422f334a6b46a19448ad59aaffdfc0a36b08fdcc1c749a0b29b6453d7e59" - name = "github.com/valyala/bytebufferpool" - packages = ["."] - pruneopts = "UT" - revision = "e746df99fe4a3986f4d4f79e13c1e0117ce9c2f7" - version = "v1.0.0" - -[[projects]] - branch = "master" - digest = "1:7e12ccc0a8e49d3b71d2f38df60eeadf6108e181d1b2eb53983d413cabe3d222" - name = "github.com/valyala/fasthttp" - packages = [ - ".", - "fasthttputil", - "stackless", - ] - pruneopts = "UT" - revision = "f544170d6384e251aa6657e55bac36c999c86e7a" - [[projects]] digest = "1:39a425f98fb19427061a693fe6bf0683c9bddec4b25b17067e34fdb465e39cb9" name = "github.com/x-cray/logrus-prefixed-formatter" @@ -468,18 +384,15 @@ [[projects]] branch = "master" - digest = "1:35ce874cf16f78a2da908ab28b0277497e36603d289db00d39da5200bc8ace08" + digest = "1:bbe51412d9915d64ffaa96b51d409e070665efc5194fcf145c4a27d4133107a4" name = "golang.org/x/crypto" - packages = [ - "pbkdf2", - "ssh/terminal", - ] + packages = ["ssh/terminal"] pruneopts = "UT" - revision = "cbcb750295291b33242907a04be40e80801d0cfc" + revision = "4def268fd1a49955bfb3dda92fe3db4f924f2285" [[projects]] branch = "master" - digest = "1:07c70ed7db30e61c8e28f5139a426deef24d6be14a16a679f2c38e89b1704475" + digest = "1:d2aa096fe6b539afe74dd6ab8e9a160304707f1477b01c637b4bbe20d262a25c" name = "golang.org/x/net" packages = [ "context", @@ -491,18 +404,18 @@ "trace", ] pruneopts = "UT" - revision = "a4d6f7feada510cc50e69a37b484cb0fdc6b7876" + revision = "ca1201d0de80cfde86cb01aea620983605dfe99b" [[projects]] branch = "master" - digest = "1:646036a04e163f383d101f40e36fd3354676c7dcccc226d825200a6b9509727a" + digest = "1:16c3c95c0f98e5bff7c863065da66f1e747bced6f101281c041060830842ebc1" name = "golang.org/x/sys" packages = [ "unix", "windows", ] pruneopts = "UT" - revision = "a5b02f93d862f065920dd6a40dddc66b60d0dec4" + revision = "cbf593c0f2f39034e9104bbf77e2ec7c48c98fc5" [[projects]] digest = "1:8d8faad6b12a3a4c819a3f9618cb6ee1fa1cfc33253abeeea8b55336721e3405" @@ -531,20 +444,17 @@ [[projects]] branch = "master" - digest = "1:585235ddbee27460066b51a01507349225137f1442cb9cf273321b4617c599c5" + 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 = "b515fa19cec88c32f305a962f34ae60068947aea" + revision = "c506a9f9061087022822e8da603a52fc387115a8" [[projects]] - digest = "1:707c3a5d10ed430ea767d73df122d9eb3dfb6312bbacc9f2e39204390686d1d0" + digest = "1:581c9b0fe9354faf730ff231cf3682089e0b703073cf10e3976219609d27a9ea" name = "google.golang.org/grpc" packages = [ ".", @@ -576,13 +486,14 @@ "resolver", "resolver/dns", "resolver/passthrough", + "serviceconfig", "stats", "status", "tap", ] pruneopts = "UT" - revision = "25c4f928eaa6d96443009bd842389fb4fa48664e" - version = "v1.20.1" + revision = "045159ad57f3781d409358e3ade910a018c16b30" + version = "v1.22.1" [[projects]] digest = "1:4d2e5a73dc1500038e504a8d78b986630e3626dc027bc030ba5c75da257cdb96" @@ -592,45 +503,24 @@ revision = "51d6538a90f86fe93ac480b35f37b2be17fef232" version = "v2.2.2" -[[projects]] - digest = "1:999d566ad1ae4303c456af5a155f7b42401cca4fd33552567ed9dd997b107a08" - name = "mellium.im/sasl" - packages = ["."] - pruneopts = "UT" - revision = "e58e780e1378aa4df5dc705364ff5ae9a4dd1e04" - source = "https://github.com/mellium/sasl.git" - version = "v0.2.1" - [solve-meta] analyzer-name = "dep" analyzer-version = 1 input-imports = [ - "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/raft", + "github.com/hashicorp/raft-boltdb", + "github.com/integration-system/golang-socketio", "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", - "google.golang.org/grpc", - "google.golang.org/grpc/codes", - "google.golang.org/grpc/grpclog", - "google.golang.org/grpc/status", + "github.com/json-iterator/go", + "github.com/mohae/deepcopy", + "github.com/pkg/errors", + "github.com/thecodeteam/goodbye", ] solver-name = "gps-cdcl" solver-version = 1 diff --git a/Gopkg.toml b/Gopkg.toml index 1b2b5b8..570ab69 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -36,10 +36,3 @@ name = "github.com/valyala/fasthttp" branch = "master" -[[override]] - name = "github.com/googollee/go-socket.io" - revision = "c8aeb1ed9b49d7de8fef8662efb18f1d289c5f2e" - -[[override]] - name = "github.com/googollee/go-engine.io" - revision = "e2f255711dcb2ea41e42c6d9d98c172d7edf6509" diff --git a/cluster/client.go b/cluster/client.go new file mode 100644 index 0000000..6d1b584 --- /dev/null +++ b/cluster/client.go @@ -0,0 +1,94 @@ +package cluster + +import ( + "errors" + "github.com/integration-system/isp-lib/logger" + "isp-config-service/raft" + "sync" + "time" +) + +var ( + ErrNoLeader = errors.New("no leader in cluster") + ErrLeaderClientNotInitialized = errors.New("leader client not initialized") +) + +const ( + leaderConnectionTimeout = 3 * time.Second + defaultApplyTimeout = 3 * time.Second +) + +type ClusterClient struct { + r *raft.Raft + + leaderMu sync.RWMutex + leaderState leaderState + leaderClient *SocketLeaderClient +} + +func (client *ClusterClient) Shutdown() error { + return client.r.GracefulShutdown() +} + +func (client *ClusterClient) SyncApply(command []byte) (interface{}, error) { + client.leaderMu.RLock() + defer client.leaderMu.Unlock() + + if !client.leaderState.leaderElected { + return nil, ErrNoLeader + } + + if client.leaderState.isLeader { + return client.r.SyncApply(command) + } else { + if client.leaderClient == nil { + return nil, ErrLeaderClientNotInitialized + } + return client.leaderClient.Send(command, defaultApplyTimeout) + } +} + +func (client *ClusterClient) listenLeader() { + for n := range client.r.LeaderCh() { + logger.Debug(n) + + client.leaderMu.Lock() + if client.leaderState.leaderAddr != n.CurrentLeaderAddress { + if client.leaderClient != nil { + client.leaderClient.Close() + client.leaderClient = nil + } + } + if n.LeaderElected && !n.IsLeader { + leaderClient := NewSocketLeaderClient(n.CurrentLeaderAddress) + if err := leaderClient.Dial(leaderConnectionTimeout); err != nil { + logger.Fatalf("could not connect to leader: %v", err) + continue + } + client.leaderClient = leaderClient + } + 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) *ClusterClient { + client := &ClusterClient{ + r: r, + leaderState: leaderState{}, + } + go client.listenLeader() + + return client +} diff --git a/cluster/command.go b/cluster/command.go new file mode 100644 index 0000000..d384a7b --- /dev/null +++ b/cluster/command.go @@ -0,0 +1,49 @@ +package cluster + +import ( + "github.com/pkg/errors" + "isp-config-service/entity" +) + +type CommandType int + +const ( + UpdateModule CommandType = iota + DeleteModule + UpdateConfiguration + DeleteConfiguration + UpdateSchema + DeleteSchema +) + +type Command interface { + Apply(s State) State +} + +type UpdateModuleCommand struct { + Module entity.Module +} + +type operation struct { + Command CommandType + Payload []byte +} + +func UnmarshalCommand(data []byte) (Command, error) { + op := operation{} + if err := json.Unmarshal(data, &op); err != nil { + return nil, errors.WithMessage(err, "unmarshal operation") + } + + switch op.Command { + case UpdateModule: + + case DeleteModule: + case UpdateConfiguration: + case DeleteConfiguration: + case UpdateSchema: + case DeleteSchema: + } + + return nil, nil +} diff --git a/cluster/const.go b/cluster/const.go new file mode 100644 index 0000000..7d926c6 --- /dev/null +++ b/cluster/const.go @@ -0,0 +1,5 @@ +package cluster + +const ( + applyCommandEvent = "CONFIG_CLUSTER:APPLY_COMMAND" +) diff --git a/cluster/leader_client.go b/cluster/leader_client.go new file mode 100644 index 0000000..fa728ad --- /dev/null +++ b/cluster/leader_client.go @@ -0,0 +1,53 @@ +package cluster + +import ( + "github.com/cenkalti/backoff" + gosocketio "github.com/integration-system/golang-socketio" + "github.com/integration-system/isp-lib/config" + "github.com/integration-system/isp-lib/logger" + "isp-config-service/conf" + "net" + "time" +) + +type SocketLeaderClient struct { + c *gosocketio.Client +} + +func (c *SocketLeaderClient) Send(data []byte, timeout time.Duration) (string, error) { + return c.c.Ack(applyCommandEvent, data, timeout) +} + +func (c *SocketLeaderClient) Dial(timeout time.Duration) error { + backOff := backoff.NewExponentialBackOff() + backOff.MaxElapsedTime = timeout + return backoff.Retry(c.c.Dial, backOff) +} + +func (c *SocketLeaderClient) Close() { + c.c.Close() +} + +func NewSocketLeaderClient(address string) *SocketLeaderClient { + socketIoAddress := getSocketIoAddress(address) + client := gosocketio.NewClientBuilder(). + EnableReconnection(). + ReconnectionTimeout(1 * time.Second). + OnReconnectionError(func(err error) { + logger.Warnf("socket.io leader(%s) client reconnection err: %v", socketIoAddress, err) + }). + BuildToConnect(socketIoAddress) + return &SocketLeaderClient{ + c: client, + } +} + +func getSocketIoAddress(address string) string { + addr, err := net.ResolveTCPAddr("tcp", address) + if err != nil { + panic(err) //must never occured + } + + cfg := config.Get().(*conf.Configuration) + return net.JoinHostPort(addr.IP.String(), cfg.WS.Rest.Port) +} diff --git a/cluster/state.go b/cluster/state.go new file mode 100644 index 0000000..862b450 --- /dev/null +++ b/cluster/state.go @@ -0,0 +1,10 @@ +package cluster + +import "isp-config-service/entity" + +type State struct { + Configurations map[int64]entity.Config + Modules map[int32]entity.Module + Instances map[int32]entity.Instance + Schemas map[int32]entity.ConfigSchema +} diff --git a/cluster/store.go b/cluster/store.go new file mode 100644 index 0000000..da9bba3 --- /dev/null +++ b/cluster/store.go @@ -0,0 +1,75 @@ +package cluster + +import ( + "github.com/hashicorp/raft" + jsoniter "github.com/json-iterator/go" + "github.com/mohae/deepcopy" + "github.com/pkg/errors" + "io" + "sync" +) + +var ( + json = jsoniter.ConfigFastest +) + +type Store struct { + state State + lock sync.Mutex +} + +func (f *Store) Apply(l *raft.Log) interface{} { + f.lock.Lock() + defer f.lock.Unlock() + return nil +} + +// Snapshot returns a snapshot of the key-value store. +func (f *Store) Snapshot() (raft.FSMSnapshot, error) { + f.lock.Lock() + defer f.lock.Unlock() + + copied := deepcopy.Copy(f.state).(State) + + return &fsmSnapshot{copied}, nil +} + +// Restore stores the key-value store to a previous state. +func (f *Store) Restore(rc io.ReadCloser) error { + s := State{} + + if err := json.NewDecoder(rc).Decode(&s); err != nil { + return errors.WithMessage(err, "unmarshal state") + } + + f.state = s + + return nil +} + +type fsmSnapshot struct { + state State +} + +func (f *fsmSnapshot) Persist(sink raft.SnapshotSink) error { + err := func() error { + b, err := json.Marshal(f.state) + if err != nil { + return err + } + + if _, err := sink.Write(b); err != nil { + return err + } + + return sink.Close() + }() + + if err != nil { + _ = sink.Cancel() + } + + return err +} + +func (f *fsmSnapshot) Release() {} diff --git a/conf/config.yml b/conf/config.yml index 39f3f9c..fbc0763 100644 --- a/conf/config.yml +++ b/conf/config.yml @@ -19,6 +19,9 @@ ws: grpc: port: "9002" ip: "0.0.0.0" + raft: + port: "9003" + ip: "0.0.0.0" metrics: gc: true @@ -28,3 +31,10 @@ metrics: ip: "0.0.0.0" port: "9551" path: "/metrics" + +cluster: + dataDir: ./data + inMemory: true + outerAddress: 127.0.0.1:9003 + peers: + - 127.0.0.1:9003 diff --git a/conf/configuration.go b/conf/configuration.go index 9dc26a0..eb8d53d 100644 --- a/conf/configuration.go +++ b/conf/configuration.go @@ -11,6 +11,15 @@ type Configuration struct { WS struct { Rest structure.AddressConfiguration `valid:"required~Required"` Grpc structure.AddressConfiguration `valid:"required~Required"` + Raft structure.AddressConfiguration `valid:"required~Required"` } Metrics structure.MetricConfiguration + Cluster ClusterConfiguration `valid:"required~Required"` +} + +type ClusterConfiguration struct { + InMemory bool + DataDir string `valid:"required~Required"` + Peers []string `valid:"required~Required"` + OuterAddress string `valid:"required~Required"` } diff --git a/controllers/config.go b/controllers/config.go deleted file mode 100644 index e20a5e1..0000000 --- a/controllers/config.go +++ /dev/null @@ -1,125 +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" -) - -func GetConfigs(identities []int64) ([]st.Config, error) { - configs, err := model.ConfigRep.GetConfigs(identities) - if err != nil { - return nil, createUnknownError(err) - } - return configs, nil -} - -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 -} - -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 -} - -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 -} diff --git a/controllers/instance.go b/controllers/instance.go deleted file mode 100644 index 5f335d4..0000000 --- a/controllers/instance.go +++ /dev/null @@ -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) -} diff --git a/controllers/jsonController.go b/controllers/jsonController.go deleted file mode 100644 index 55a2c8d..0000000 --- a/controllers/jsonController.go +++ /dev/null @@ -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) -}) -*/ diff --git a/controllers/module.go b/controllers/module.go deleted file mode 100644 index dfa2c00..0000000 --- a/controllers/module.go +++ /dev/null @@ -1,113 +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" -) - -func GetModules(identities []int32) ([]st.Module, error) { - modules, err := model.ModulesRep.GetModules(identities) - if err != nil { - return nil, createUnknownError(err) - } - - return modules, nil -} - -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 -} diff --git a/controllers/route.go b/controllers/route.go deleted file mode 100644 index 14b5421..0000000 --- a/controllers/route.go +++ /dev/null @@ -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 -} diff --git a/domain/request.go b/domain/request.go deleted file mode 100644 index 8ab794b..0000000 --- a/domain/request.go +++ /dev/null @@ -1,15 +0,0 @@ -package domain - -type IdentitiesRequest struct { - Ids []int32 `json:"ids" 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"` -} diff --git a/domain/response.go b/domain/response.go deleted file mode 100644 index b3b208c..0000000 --- a/domain/response.go +++ /dev/null @@ -1,34 +0,0 @@ -package domain - -import ( - "time" - - "isp-config-service/entity" - - "github.com/integration-system/isp-lib/config/schema" - "github.com/integration-system/isp-lib/structure" -) - -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 - 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"` -} diff --git a/entity/instance.go b/entity/instance.go index 222f080..fb4ddd4 100644 --- a/entity/instance.go +++ b/entity/instance.go @@ -1,8 +1,6 @@ package entity -import ( - "time" -) +import "time" type Instance struct { Id int32 `json:"id"` diff --git a/entity/module.go b/entity/module.go index 8c19255..bd0c3bf 100644 --- a/entity/module.go +++ b/entity/module.go @@ -1,8 +1,6 @@ package entity -import ( - "time" -) +import "time" type Module struct { Id int32 `json:"id"` diff --git a/generated/backend_service.pb.go b/generated/backend_service.pb.go deleted file mode 100644 index c7c6ff9..0000000 --- a/generated/backend_service.pb.go +++ /dev/null @@ -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, -} diff --git a/generated/backend_service.pb.gw.go b/generated/backend_service.pb.gw.go deleted file mode 100644 index b7fa6f9..0000000 --- a/generated/backend_service.pb.gw.go +++ /dev/null @@ -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 -) diff --git a/helper/handler.go b/helper/handler.go index ef43494..5fcd9db 100644 --- a/helper/handler.go +++ b/helper/handler.go @@ -1,58 +1,5 @@ package helper -import ( - "github.com/integration-system/isp-lib/structure" - "isp-config-service/controllers" - "isp-config-service/domain" - "isp-config-service/entity" -) - -type Handlers struct { - // ===== INSTANCE ===== - GetInstances func(identities []int32) ([]entity.Instance, error) `method:"get_instances" group:"instance" inner:"true"` - CreateUpdateInstance func(instance entity.Instance) (*entity.Instance, error) `method:"create_update_instance" group:"instance" inner:"true"` - DeleteInstance func(identities []int32) (*domain.DeleteResponse, error) `method:"delete_instance" group:"instance" inner:"true"` - - // ===== MODULE ===== - GetModules func(identities []int32) ([]entity.Module, error) `method:"get_modules" group:"module" inner:"true"` - GetActiveModules func() ([]entity.Module, error) `method:"get_active_modules" group:"module" inner:"true"` - GetConnectedModules func() (map[string]interface{}, error) `method:"get_connected_modules" group:"module" inner:"true"` - CreateUpdateModule func(module entity.Module) (*entity.Module, error) `method:"create_update_module" group:"module" inner:"true"` - DeleteModule func(identities []int32) (*domain.DeleteResponse, error) `method:"delete_module" group:"module" inner:"true"` - GetModulesInfo func(i structure.Isolation) ([]*domain.ModuleInfo, error) `method:"get_modules_info" group:"module" inner:"true"` - - // ===== CONFIG ===== - GetConfigs func(identities []int64) ([]entity.Config, error) `method:"get_configs" group:"config" inner:"true"` - GetConfigByInstanceUUIDAndModuleName func(request entity.ModuleInstanceIdentity) (*entity.Config, error) `method:"get_config_by_instance_uuid_and_module_name" group:"config" inner:"true"` - CreateUpdateConfig func(config entity.Config) (*entity.Config, error) `method:"create_update_config" group:"config" inner:"true"` - UpdateActiveConfigByInstanceUUIDAndModuleName func(config domain.ConfigInstanceModuleName) (*entity.Config, error) `method:"update_active_config_by_instance_uuid_and_module_name" group:"config" inner:"true"` - MarkConfigAsActive func(identity domain.LongIdentitiesRequest) (*entity.Config, error) `method:"mark_config_as_active" group:"config" inner:"true"` - DeleteConfig func(identities []int64) (*domain.DeleteResponse, error) `method:"delete_config" group:"config" inner:"true"` - - // ===== ROUTING ===== - GetRoutes func() (map[string]interface{}, error) `method:"get_routes" group:"routing" inner:"true"` -} - -func GetHandlers() *Handlers { - return &Handlers{ - GetInstances: controllers.GetInstances, - CreateUpdateInstance: controllers.CreateUpdateInstance, - DeleteInstance: controllers.DeleteInstance, - - GetModules: controllers.GetModules, - GetActiveModules: controllers.GetActiveModules, - GetConnectedModules: controllers.GetConnectedModules, - CreateUpdateModule: controllers.CreateUpdateModule, - DeleteModule: controllers.DeleteModule, - GetModulesInfo: controllers.GetModulesAggregatedInfo, - - GetConfigs: controllers.GetConfigs, - GetConfigByInstanceUUIDAndModuleName: controllers.GetConfigByInstanceUUIDAndModuleName, - CreateUpdateConfig: controllers.CreateUpdateConfig, - UpdateActiveConfigByInstanceUUIDAndModuleName: controllers.UpdateActiveConfigByInstanceUUIDAndModuleName, - MarkConfigAsActive: controllers.MarkConfigAsActive, - DeleteConfig: controllers.DeleteConfig, - - GetRoutes: controllers.GetRoutes, - } +func GetAllHandlers() []interface{} { + return nil } diff --git a/holder/holder.go b/holder/holder.go new file mode 100644 index 0000000..3dfaaa9 --- /dev/null +++ b/holder/holder.go @@ -0,0 +1,13 @@ +package holder + +import ( + "isp-config-service/cluster" + "isp-config-service/ws" + "net/http" +) + +var ( + ClusterClient *cluster.ClusterClient + Socket *ws.WebsocketServer + HttpServer *http.Server +) diff --git a/main.go b/main.go index 769efc2..581545c 100644 --- a/main.go +++ b/main.go @@ -1,234 +1,108 @@ 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" "github.com/integration-system/isp-lib/backend" "github.com/integration-system/isp-lib/config" - "github.com/integration-system/isp-lib/database" "github.com/integration-system/isp-lib/logger" - "github.com/integration-system/isp-lib/metric" "github.com/integration-system/isp-lib/structure" - "github.com/integration-system/isp-lib/utils" - "golang.org/x/net/context" - "google.golang.org/grpc" + "github.com/thecodeteam/goodbye" + "isp-config-service/cluster" + "isp-config-service/conf" + "isp-config-service/helper" + "isp-config-service/holder" + "isp-config-service/raft" + "isp-config-service/ws" + "net/http" + "os" ) const ( - routerModule = "router" - converterModule = "converter" + moduleName = "config" ) var ( - configData *conf.Configuration - echoEndpoint *string - version = "0.1.0" - date = "undefined" + version = "0.1.0" + date = "undefined" + + shutdownChan = make(chan struct{}) ) 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{}) } 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) + cfg := config.Get().(*conf.Configuration) - createGrpcServer() - createRestServer(runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{OrigName: true, EmitDefaults: true})) -} + initWebsocket(cfg.WS.Rest.GetAddress()) + initRaft(cfg.WS.Raft.GetAddress(), cfg.Cluster) + initGrpc(cfg.WS.Grpc) -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. - handlers := helper.GetHandlers() - addr := structure.AddressConfiguration{IP: configData.WS.Grpc.IP, Port: configData.WS.Grpc.Port} - addrOuter := structure.AddressConfiguration{IP: configData.GrpcOuterAddress.IP, Port: configData.GrpcOuterAddress.Port} - backend.StartBackendGrpcServer(addr, backend.GetDefaultService(configData.ModuleName, handlers)) - enndpoints := backend.GetEndpoints(configData.ModuleName, handlers) - - socket.SetBackendMethods(&structure.BackendDeclaration{ - ModuleName: configData.ModuleName, - Version: version, - LibVersion: bootstrap.LibraryVersion, - Endpoints: enndpoints, - Address: addrOuter, - }) - logger.Infof("EXPORTED MODULE METHODS: %v, module_name: %s, version: %s", - enndpoints, configData.ModuleName, version) -} - -// Start a HTTP server. -func createRestServer(opts ...runtime.ServeMuxOption) { - - mux := http.NewServeMux() ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() + defer goodbye.Exit(ctx, -1) + goodbye.Notify(ctx) + goodbye.Register(onShutdown) - // === Socket.IO === - mux.Handle("/socket.io/", socket.Get()) + <-shutdownChan +} - // === 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 initWebsocket(bindAddress string) { + socket, err := ws.NewWebsocketServer() if err != nil { - logger.Fatalf("failed to serve: %v", err) + logger.Fatal(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. - } - + mux := http.NewServeMux() + mux.HandleFunc("/socket.io/", socket.ServeHttp) + httpServer := &http.Server{Addr: bindAddress, Handler: mux} go func() { - if err := srv.ListenAndServe(); err != nil { + if err := httpServer.ListenAndServe(); err != nil { logger.Fatal(err) } }() + holder.Socket = socket + holder.HttpServer = httpServer - c := make(chan os.Signal, 1) - // We'll accept graceful shutdowns when quit via SIGINT (Ctrl+C) - // SIGKILL, SIGQUIT or SIGTERM (Ctrl+/) will not be caught. - signal.Notify(c, os.Interrupt) - - // Block until we receive our signal. - <-c - - // Create a deadline to wait for. - ctx, cancel = context.WithTimeout(context.Background(), wait) - defer cancel() - // Doesn't block if no connections, but will otherwise wait - // until the timeout deadline. - _ = srv.Shutdown(ctx) - // Optionally, you could run srv.Shutdown in a goroutine and block on - // <-ctx.Done() if your application should wait for other services - // to finalize based on context cancellation. - logger.Info("shutting down") - os.Exit(0) + logger.Infof("socket.IO server start on %s", bindAddress) } -func handleModulesRequest(ctx *fasthttp.RequestCtx) { - instances, err := model.InstanceRep.GetInstances(nil) +func initRaft(bindAddress string, clusterCfg conf.ClusterConfiguration) { + r, err := raft.NewRaft(bindAddress, clusterCfg) if err != nil { - logger.Warn(err) - ctx.Error("internal server error", http.StatusInternalServerError) - return + logger.Fatal(err) } + holder.ClusterClient = cluster.NewRaftClusterClient(r) - 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 - } + _ = r.BootstrapCluster() // err can be ignored - for _, inf := range info { - inf.ConfigSchema = nil - inf.Configs = nil - for i := range inf.Status { - s := &inf.Status[i] - s.Endpoints = nil - } - } + logger.Infof("raft server start on %s", bindAddress) +} - result[i.Uuid] = info - } +func initGrpc(bindAddress structure.AddressConfiguration) { + service := backend.GetDefaultService(moduleName, helper.GetAllHandlers()...) + backend.StartBackendGrpcServer(bindAddress, service) +} - if bytes, err := utils.ConvertInterfaceToBytes(result, nil); err != nil { - logger.Warn(err) - ctx.Error("internal server error", http.StatusInternalServerError) +func onShutdown(ctx context.Context, sig os.Signal) { + defer close(shutdownChan) + + backend.StopGrpcServer() + + if err := holder.ClusterClient.Shutdown(); err != nil { + logger.Warnf("raft shutdown err: %v", err) } else { - ctx.SetStatusCode(http.StatusOK) - ctx.SetContentType("application/json; charset=utf-8") - ctx.SetBody(bytes) + logger.Info("raft shutdown success") + } + + if err := holder.Socket.Close(); err != nil { + logger.Info("socket.io shutdown err: %v", err) + } else { + logger.Info("socket.io shutdown success") + } + + if err := holder.HttpServer.Shutdown(ctx); err != nil { + logger.Info("http server shutdown err: %v", err) + } else { + logger.Info("http server shutdown success") } } diff --git a/migrations_temp/00002_2018-04-05_create_instances_table.sql b/migrations/00002_2018-04-05_create_instances_table.sql similarity index 100% rename from migrations_temp/00002_2018-04-05_create_instances_table.sql rename to migrations/00002_2018-04-05_create_instances_table.sql diff --git a/migrations_temp/00003_2018-04-05_create_modules_table.sql b/migrations/00003_2018-04-05_create_modules_table.sql similarity index 100% rename from migrations_temp/00003_2018-04-05_create_modules_table.sql rename to migrations/00003_2018-04-05_create_modules_table.sql diff --git a/migrations_temp/00004_2018-04-05_create_configs_table.sql b/migrations/00004_2018-04-05_create_configs_table.sql similarity index 100% rename from migrations_temp/00004_2018-04-05_create_configs_table.sql rename to migrations/00004_2018-04-05_create_configs_table.sql diff --git a/migrations_temp/00010_2018-07-31_add_name_for_configs.sql b/migrations/00005_2018-07-31_add_name_for_configs.sql similarity index 100% rename from migrations_temp/00010_2018-07-31_add_name_for_configs.sql rename to migrations/00005_2018-07-31_add_name_for_configs.sql diff --git a/migrations_temp/00011_2018-07-31_config_sheme_table.sql b/migrations/00006_2018-07-31_config_sheme_table.sql similarity index 100% rename from migrations_temp/00011_2018-07-31_config_sheme_table.sql rename to migrations/00006_2018-07-31_config_sheme_table.sql diff --git a/migrations_temp/00001_2018-04-05_create_schema.sql b/migrations_temp/00001_2018-04-05_create_schema.sql deleted file mode 100644 index 091ab13..0000000 --- a/migrations_temp/00001_2018-04-05_create_schema.sql +++ /dev/null @@ -1,5 +0,0 @@ --- +goose Up -CREATE schema if NOT EXISTS "config_service"; - --- +goose Down -DROP schema if EXISTS config_service CASCADE; \ No newline at end of file diff --git a/migrations_temp/00005_2018-06-14_add_default_instance.sql b/migrations_temp/00005_2018-06-14_add_default_instance.sql deleted file mode 100644 index a34223c..0000000 --- a/migrations_temp/00005_2018-06-14_add_default_instance.sql +++ /dev/null @@ -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 diff --git a/migrations_temp/00006_2018-06-14_add_default_system_modules.sql b/migrations_temp/00006_2018-06-14_add_default_system_modules.sql deleted file mode 100644 index 5974380..0000000 --- a/migrations_temp/00006_2018-06-14_add_default_system_modules.sql +++ /dev/null @@ -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); diff --git a/migrations_temp/00007_2018-06-14_add_default_modules.sql b/migrations_temp/00007_2018-06-14_add_default_modules.sql deleted file mode 100644 index b3dce86..0000000 --- a/migrations_temp/00007_2018-06-14_add_default_modules.sql +++ /dev/null @@ -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); diff --git a/migrations_temp/00008_2018-06-14_add_default_system_module_configs.sql b/migrations_temp/00008_2018-06-14_add_default_system_module_configs.sql deleted file mode 100644 index bdc14b6..0000000 --- a/migrations_temp/00008_2018-06-14_add_default_system_module_configs.sql +++ /dev/null @@ -1,58 +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'; - --- auth -INSERT INTO configs VALUES (1, 1, NULL, 't', NULL, NULL, ('{"redis": {' || - '"ip": "' || current_setting('migration.redis_host') || '", ' || - '"port": ' || current_setting('migration.redis_port') || - '}, "header": {"token": {"user": "X-USER-TOKEN", "device": "X-DEVICE-TOKEN", "application": "X-APPLICATION-TOKEN"}, "identity": {"user": "X-USER-IDENTITY", "device": "X-DEVICE-IDENTITY", "domain": "X-DOMAIN-IDENTITY", "system": "X-SYSTEM-IDENTITY", "service": "X-SERVICE-IDENTITY", "application": "X-APPLICATION-IDENTITY"}}, "unauthorized.html": "
>>u&mn;if(_!==h>>>u&mn)break;_&&(c+=(1<i&&(l=l.removeBefore(r,u,a-c)),l&&h
a&&(a=l.size),o(u)||(l=l.map(function(e){return H(e)})),i.push(l)}return a>e.size&&(e=e.setSize(a)),Ie(e,t,i)}function $e(e){return es)return k();var e=i.next();return r||t===bn?e:t===_n?w(t,u-1,void 0,e):w(t,u-1,e.value[1],e)})},l}function dt(e,t,n){var r=Dt(e);return r.__iterateUncached=function(r,i){var o=this;if(i)return this.cacheResult().__iterate(r,i);var a=0;return e.__iterate(function(e,i,s){return t.call(n,e,i,s)&&++a&&r(e,i,o)}),a},r.__iteratorUncached=function(r,i){var o=this;if(i)return this.cacheResult().__iterator(r,i);var a=e.__iterator(xn,i),s=!0;return new x(function(){if(!s)return k();var e=a.next();if(e.done)return e;var i=e.value,u=i[0],l=i[1];return t.call(n,l,u,o)?r===xn?e:w(r,u,l,e):(s=!1,k())})},r}function mt(e,t,n,r){var i=Dt(e);return i.__iterateUncached=function(i,o){var a=this;if(o)return this.cacheResult().__iterate(i,o);var s=!0,u=0;return e.__iterate(function(e,o,l){if(!s||!(s=t.call(n,e,o,l)))return u++,i(e,r?o:u-1,a)}),u},i.__iteratorUncached=function(i,o){var a=this;if(o)return this.cacheResult().__iterator(i,o);var s=e.__iterator(xn,o),u=!0,l=0;return new x(function(){var e,o,c;do{if(e=s.next(),e.done)return r||i===bn?e:i===_n?w(i,l++,void 0,e):w(i,l++,e.value[1],e);var p=e.value;o=p[0],c=p[1],u&&(u=t.call(n,c,o,a))}while(u);return i===xn?e:w(i,o,c,e)})},i}function vt(e,t){var r=a(e),i=[e].concat(t).map(function(e){return o(e)?r&&(e=n(e)):e=r?L(e):q(Array.isArray(e)?e:[e]),e}).filter(function(e){return 0!==e.size});if(0===i.length)return e;if(1===i.length){var u=i[0];if(u===e||r&&a(u)||s(e)&&s(u))return u}var l=new I(i);return r?l=l.toKeyedSeq():s(e)||(l=l.toSetSeq()),l=l.flatten(!0),l.size=i.reduce(function(e,t){if(void 0!==e){var n=t.size;if(void 0!==n)return e+n}},0),l}function gt(e,t,n){var r=Dt(e);return r.__iterateUncached=function(r,i){function a(e,l){var c=this;e.__iterate(function(e,i){return(!t||l=Vn)return Oe(e,f,l,s,d);if(c&&!d&&2===f.length&&Se(f[1^p]))return f[1^p];if(c&&d&&1===f.length&&Se(d))return d;var m=e&&e===this.ownerID,v=c?d?l:l^u:l|u,g=c?d?Ne(f,p,d,m):Be(f,p,m):Fe(f,p,d,m);return m?(this.bitmap=v,this.nodes=g,this):new de(e,v,g)},me.prototype.get=function(e,t,n,r){void 0===t&&(t=oe(n));var i=(0===e?t:t>>>e)&mn,o=this.nodes[i];return o?o.get(e+hn,t,n,r):r},me.prototype.update=function(e,t,n,r,i,o,a){void 0===n&&(n=oe(r));var s=(0===t?n:n>>>t)&mn,u=i===vn,l=this.nodes,c=l[s];if(u&&!c)return this;var p=Ee(c,e,t+hn,n,r,i,o,a);if(p===c)return this;var f=this.count;if(c){if(!p&&--f5?l-5:0),p=5;p5?l-5:0),p=5;ps&&(n=s-u),l=n;l>=0;l--){for(var p=!0,f=0;fi&&(r=i):r=i;var o=t.length;if(o%2!=0)throw new TypeError("Invalid hex string");r>o/2&&(r=o/2);for(var a=0;a