Compare commits

..

1785 Commits

Author SHA1 Message Date
e13c2c48fd client: use router.DefaultRouter in NewOptions helper
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-03-26 17:45:55 +03:00
8db55d2e55 router: use dns as default router
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-03-26 17:43:39 +03:00
ed61cad961 meter/handler: regen
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-03-26 15:45:09 +03:00
040fc4548f client: add TLSConfig option
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-03-26 15:44:34 +03:00
6189a1b980 add SkipEndpoints for wrappers
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-03-25 23:30:38 +03:00
eb2a450a7b meter/handler: fix func signature
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-03-25 12:36:48 +03:00
Renovate Bot
d2a30a5da1 fix(deps): update golang.org/x/net commit hash to d1beb07 2021-03-24 23:28:38 +00:00
65889c66f6 meter/wrapper: add DefaultSkipEndpoints
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-03-25 00:06:38 +03:00
dcdf133d5b server: mask router
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-03-24 13:26:36 +03:00
8742b55305 auth: fix Init method
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-03-24 13:12:03 +03:00
4a64ee72f7 meter/handler: provide default metrics handler
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-03-23 17:26:29 +03:00
881d7afeea meter/handler: provide initial meter handler
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-03-23 17:12:13 +03:00
8c95448535 util/reflect: add IsZero helper
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-03-21 16:17:50 +03:00
c1dc041d8c client: fix NewOptions with CallOptions filling
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-03-16 19:09:49 +03:00
Renovate Bot
25be0ac0f0 fix(deps): update golang.org/x/net commit hash to d523dce 2021-03-16 13:12:17 +00:00
Renovate Bot
86f73cac4e fix(deps): update golang.org/x/net commit hash to 34ac3e1 2021-03-15 22:09:13 +00:00
485eda6ce9 meter/wrapper: fix wrapper build
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-03-15 00:49:26 +03:00
dbbdb24631 meter: rework labels
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-03-15 00:44:13 +03:00
723ceb4f32 regsiter: fix extractor
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-03-12 16:09:20 +03:00
bac9869bb3 register: support map in ExtractValue
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-03-12 15:48:05 +03:00
610427445f codec: provide proto for codec.Frame
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-03-11 07:42:42 +03:00
Renovate Bot
c84a66c713 fix(deps): update module github.com/imdario/mergo to v0.3.12 2021-03-10 00:35:57 +00:00
00eaae717b lint fixes
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-03-06 23:44:54 +03:00
a102e95433 spell fixes
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-03-06 23:33:37 +03:00
39f66cc86c add logger wrapper, fix default logger fields method
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-03-06 23:26:47 +03:00
bbbcb22565 fieldalignment of all structs to save memory
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-03-06 19:45:13 +03:00
cb70dfa664 meter/wrapper: use meter.DefaultMeter in NewOptions
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-03-05 17:40:03 +03:00
1f0482fbd5 tracer: finalize tracer implementation
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-03-04 01:12:16 +03:00
a862562284 fixup domain in ListServices
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-03-03 18:16:54 +03:00
c320c23913 metadata: minor fixup for NewXXXContext functions
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-03-01 13:00:53 +03:00
Renovate Bot
ae848ba8bb fix(deps): update golang.org/x/net commit hash to e18ecbb 2021-02-26 19:46:14 +00:00
Renovate Bot
8e264cbb3e fix(deps): update golang.org/x/net commit hash to 39120d0 2021-02-26 12:05:10 +00:00
Renovate Bot
54e523ab3f fix(deps): update golang.org/x/net commit hash to 3d97a24 2021-02-26 08:40:37 +00:00
09973af099 server: add error helper
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-22 00:52:18 +03:00
3247da3dd0 metadata: add Pairs helper func
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-22 00:08:05 +03:00
b505455f7c run go mod tidy in renovate update
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-21 23:55:19 +03:00
293949f081 metadata: add Append func to Incoming/Outgoing context
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-21 23:54:59 +03:00
8d7e442b3a server: add SubscriberBodyOnly option
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-20 18:12:13 +03:00
renovate[bot]
f7b5211af3 fix(deps): update golang.org/x/net commit hash to 5f55cee (#20)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-02-20 11:40:35 +03:00
7eb6d030dc meter: fix internal labels sorting
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-18 15:57:42 +03:00
47e75c31c7 meter: export labels len method
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-18 14:41:51 +03:00
20ff5eed22 meter: initial wrapper import (#19)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-18 14:35:10 +03:00
d23ca8db73 Merge pull request #18 from unistack-org/flow
flow: initial tests
2021-02-18 12:49:32 +03:00
4dd28ac720 go 1.15 => 1.16
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-18 12:49:02 +03:00
240b6016df flow: add initial flow dag
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-18 12:44:37 +03:00
cf2aa827e4 update to go 1.16
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-18 12:44:18 +03:00
5596345382 util/rand: replace all non crypto rand stuff with own rand package
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-18 12:44:18 +03:00
67748a2132 util/reflect: import own path based interface lookup
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-14 23:33:01 +03:00
c2333a9f35 gh actions not fail on lint errors
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-14 16:26:40 +03:00
4ec4c277b7 lint: fix all major issues
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-14 16:16:01 +03:00
a11dd00174 profiler: fix import
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-14 14:25:04 +03:00
cc7ebedf22 debug/profile: move to profiler interface
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-14 14:02:51 +03:00
e5bf1448f4 lint fixes
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-14 11:28:50 +03:00
f182bba6ff debug/log: remove stale files
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-13 20:01:57 +03:00
1f8810599b go.mod cleanup
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-13 15:37:33 +03:00
82248eb3b0 many lint fixes and optimizations (#17)
* util/kubernetes: drop stale files
* debug/log/kubernetes: drop stale files
* util/scope: remove stale files
* util/mdns: drop stale files
* lint fixes

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-13 15:35:56 +03:00
abb9937787 fix lint issues (#16)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-13 01:46:16 +03:00
fd5ed64729 metadata: fix nil metadata from FromIncoming/FromOutgoing context
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-12 17:10:35 +03:00
6751060d05 move memory implementations to core micro repo
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-12 16:33:16 +03:00
ef664607b4 automerge minor version updates
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-12 11:48:09 +03:00
62e482a14b move renovate
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-10 12:44:56 +03:00
a390ebf80f fix renovate.json
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-10 12:43:29 +03:00
9a44960be7 another fix
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-10 10:52:33 +03:00
c846c59b9b fix renovate.json
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-10 10:39:37 +03:00
renovate[bot]
902bf6326b chore(deps): update golangci/golangci-lint-action action to v2 (#14)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-02-10 00:35:56 +03:00
renovate[bot]
bddf3bf502 chore(deps): update actions/setup-go action to v2 (#13)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-02-09 23:04:23 +03:00
renovate[bot]
284131da98 Add renovate.json (#12)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
Co-authored-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-09 23:01:50 +03:00
927c7ea3c2 metadata: allow to modify metadata via SetXXX functions
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-09 12:46:14 +03:00
0e51a79bb6 metadata: split context to incoming and outgoing
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-09 01:08:45 +03:00
1de9911b73 util/reflect: add missing types for merge
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-06 18:13:43 +03:00
b4092c6619 util/reflect: improve merge for map
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-05 18:27:16 +03:00
024868bfd7 api: encode body param in endpoint
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-02 19:35:16 +03:00
a0bbfd6d02 provide compa options
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-02-02 15:37:12 +03:00
2cb6843773 codec: fix noop codec
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-01-29 23:18:12 +03:00
87e1480077 config: add name to each config imp
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-01-29 16:18:17 +03:00
bcd7f6a551 codec: fix noop codec to handle *broker.Message
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-01-29 16:07:21 +03:00
925b3af46b register: fix options
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-01-29 15:06:47 +03:00
ef4efa6a6b rename util
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-01-29 14:50:09 +03:00
125646d89b add Name func option
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-01-29 14:07:35 +03:00
7af7649448 store: add Name func
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-01-29 14:02:54 +03:00
827d467077 micro: rewrite options to support multiple building blocks
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-01-29 13:17:32 +03:00
ac8a3a12c4 meter: complete interface
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-01-27 00:54:19 +03:00
286785491c store: improve interface
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-01-26 02:09:26 +03:00
263ea8910d meter: use plan map and metadata
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-01-23 00:23:29 +03:00
202a942eef metadata: add Merge func
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-01-23 00:09:07 +03:00
c7bafecce3 add meter and tracer across all options
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-01-22 23:32:33 +03:00
c67fe6f330 meter: add option helper and provide default metric name and label prefix
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-01-22 19:18:28 +03:00
8c3f0d2c64 meter: remove wrapper
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-01-22 18:22:17 +03:00
8494178b0d meter: rework meter interface
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-01-22 18:21:40 +03:00
8a2c4c511e metadata: add iterator method
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-01-21 18:37:54 +03:00
dcca28944e util/reflect: add useful helpers
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-01-21 14:05:50 +03:00
92e6fd036e config: merge default not overwrite
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-01-21 02:20:06 +03:00
eab1a1dd40 api/server: move to dedicated repo
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-01-20 01:21:15 +03:00
188d9611c9 util/reflect: add struct field helper
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-01-20 00:47:13 +03:00
74a52eed9d rename metrics to meter
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-01-19 16:26:00 +03:00
770e8425bd config: move reflect stuff to util/reflect
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-01-19 01:40:34 +03:00
4783c6d9a3 client: add option helper
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-01-19 00:45:55 +03:00
2b2bcf4586 client: add call option helper
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-01-18 23:48:50 +03:00
77f517a9f6 metrics: add context option
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-01-15 22:47:28 +03:00
49d54f7fe6 logger: remove SetLevel from logger interface
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-01-12 09:26:14 +03:00
8b7380876e modify all code for never logger interface
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-01-10 19:24:03 +03:00
7b3a7a9448 logger: update logger interface
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-01-10 18:56:39 +03:00
270ad1b889 api: fix Decode method
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-01-10 03:55:04 +03:00
bcf7cf10d3 server: fix NewHandlerOptions
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-01-10 03:36:23 +03:00
8930c3fbb7 api/router: extend interface
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-01-10 01:54:21 +03:00
e6f870bda7 codec: fix interface
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-12-20 23:53:29 +03:00
8feab7cc48 config: init before load
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-12-20 23:08:40 +03:00
aa6afdf440 config: fix tests
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-12-20 01:07:48 +03:00
6b1ed63b48 guard agains not fully configured config sources
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-12-20 01:00:52 +03:00
b50855855b config: export method to init new empty struct
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-12-20 00:15:29 +03:00
150e8ad698 config: improve and export helper func
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-12-19 23:22:05 +03:00
035a84e696 config: fix tests
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-12-18 03:50:52 +03:00
565082f515 before/after config stuff handled by implementations
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-12-18 03:38:09 +03:00
8c504bd029 handle before/after inside config implementations
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-12-18 03:37:18 +03:00
f6c0728a59 fix context usage across codebase
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-12-17 22:52:00 +03:00
70a17dc10a client: allow to create new client with predefined call options
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-12-15 23:09:51 +03:00
f14efa64f0 server: add MaxConn and Listener options
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-12-15 11:52:05 +03:00
42f4d26fe4 server: add MaxConn option
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-12-15 11:46:30 +03:00
06c3cd6637 config: fix default config loader
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-12-13 19:28:29 +03:00
99738096ac fix configs options
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-12-13 18:56:54 +03:00
c6dfc8acaa load config on service init
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-12-13 14:36:31 +03:00
762f20d179 registry: adopt micro/micro 69b0ac2e9140fee1cde043f5ecdab438a41898ee
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-12-13 13:51:09 +03:00
92aec349c3 config: add missing codec error
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-12-13 13:26:44 +03:00
2dcd30b21c add defaut config parser
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-12-13 13:17:38 +03:00
a7a3c679d1 config: load defaults
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-12-13 13:10:04 +03:00
5c6eba20e7 codec: fix noop codec
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-12-11 00:32:29 +03:00
0a68a9c278 use default codec for store
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-12-11 00:21:53 +03:00
a13cb01005 store: create options helpers
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-12-10 22:37:40 +03:00
9fc0b5f88b store: remove unneded options
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-12-10 22:31:36 +03:00
6a7433ba2a store: refactor interface (#11)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-12-10 22:08:56 +03:00
a754ff7c0c more lint fixes
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-12-09 12:10:25 +03:00
e08276c2e2 gofmt
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-12-08 00:41:14 +03:00
b7b28f6b9a lint
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-12-08 00:38:37 +03:00
f63ff80d46 backport micro 820f59869617dee18c9a699c8e01d7a6b080f854
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-12-07 21:54:45 +03:00
8fd745eab0 config: add logger to options
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-12-07 19:27:08 +03:00
c7ed807129 default retries is always 0
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-12-07 19:26:22 +03:00
c6fd9c1c23 add context helpers
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-12-07 16:10:20 +03:00
b5d3b699cf fixup
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-12-04 02:34:20 +03:00
5279c2aa0f config package rework (#9)
* change config interface
* reuse codec
* allow to modify next config based on values in current config via BeforeLoad

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-12-04 02:28:45 +03:00
0ddc8de00b apply micro commit 2eb19c2e97d9316438bc66cd2cda896e8c99d026
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-30 22:48:00 +03:00
8d6eb34aee fix random selector
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-29 17:30:54 +03:00
0d93b2c31c add some defaults
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-26 01:13:05 +03:00
3f6852030f expose codec options
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-25 10:43:13 +03:00
458388359a add string support to noop codec
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-25 10:04:11 +03:00
2101e994d9 add Frame support in noop codec
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-25 09:59:28 +03:00
8a50a2d0b8 receives only body of the message
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-25 08:33:29 +03:00
71d82e9d5b add codec NewMessage helper
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-24 15:14:47 +03:00
c9049c3845 major codec upgrade
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-23 16:21:07 +03:00
daffa9e548 use metadata.Metadata (#8)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-18 16:50:41 +03:00
e0ef8b2953 merics: add Init func to interface
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-15 00:53:40 +03:00
f6c914c1e4 metrics: minor changes to interface and set default
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-15 00:38:38 +03:00
b38484d18e go mod tidy
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-13 15:06:12 +03:00
75222e07cb exttract protoc plugin to dedicated repo
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-13 14:59:14 +03:00
4233a4b673 init cmd and logger options on service init
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-13 14:52:19 +03:00
c44a82a8cb registry/noop: implement noop watcher
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-13 14:50:57 +03:00
37f7960f4a logger: add WithContext option
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-13 14:50:29 +03:00
6dc7e792c8 logger improvements
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-10 22:18:16 +03:00
81649d51e1 Merge branch 'master' of https://github.com/unistack-org/micro 2020-11-10 11:01:14 +03:00
23f5d10ccb server: remove unused code
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-10 11:00:37 +03:00
e3f235acc1 api/handler/rpc: fix corner cases
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-10 11:00:06 +03:00
fa9ef1c816 simplify service stop waiting
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-10 10:59:26 +03:00
77dab8ee15 server: remove unneded chan in noop server
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-10 10:58:32 +03:00
51fbff3e4a metadata: add checks for nil context
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-10 10:57:33 +03:00
bd6493327f Merge pull request #7 from itzmanish/protoc-gen-micro-fix
generate SendAndClose() and CloseAndRecv() on streams.
2020-11-07 15:53:00 +03:00
Manish
2141e9631c generate SendAndClose() and CloseAndRecv() on streams. 2020-11-07 14:55:33 +05:30
be8d09c663 network/transport: fix default dial timeout
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-06 11:18:12 +03:00
72bbbe3817 client: remove cache responses
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-06 00:25:09 +03:00
c92add984c allow to return all stuff from service opts
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-06 00:04:00 +03:00
3542d6c824 store: fix comment
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-06 00:03:40 +03:00
dc63d96e0b move store test to micro-tests repo
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-05 23:56:10 +03:00
7c9a7e84c7 not use selfsigned certs
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-05 23:55:53 +03:00
31180758b4 move avay grpc stuff to micro-server-grpc
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-05 23:46:11 +03:00
ce25a41fe1 remove cache as store can do the same thing
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-05 23:35:55 +03:00
8fa8afdfa4 fix namespace server issue
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-05 22:35:05 +03:00
e127547799 add registry helpers
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-05 21:18:05 +03:00
1fbf8b2e20 Merge pull request #6 from unistack-org/logger
rewrite logger
2020-11-05 00:49:03 +03:00
e41bb5ebc5 rewrite logger
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-05 00:23:05 +03:00
7c311aea19 api: extract routers to external repos
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-05 00:22:53 +03:00
8a2b122015 many fixes for lint and context.Context usage (#5)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-03 02:02:32 +03:00
40b0870cf8 fix linting (#4)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-03 01:08:23 +03:00
e6ab6d50eb remove unneeded Error field from broker.Message
close github.com/unistack-org/micro-roadmap/issues/26 (#3)

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-02 23:45:41 +03:00
a9eff06976 fix repocard issues (#2)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-11-02 13:25:29 +03:00
416fe5e4c8 run tests from micro-tests repo
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-10-30 23:52:05 +03:00
ddb53bf8e4 add slack badge
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-10-29 16:16:31 +03:00
0e6efda528 minor cleanup
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-10-28 17:48:39 +03:00
f2413a7789 disconnect from stuff on service stop
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-10-28 12:02:57 +03:00
9553f46cf4 connect to all stuff on start
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-10-28 10:51:09 +03:00
14c97d59c1 many improvements with options and noop stuff
* add many options helpers
* fix noop client to allow publish messages to topic in broker
* fix noop server to allow registering in registry
* fix noop server to allow subscribe to topic in broker
* fix new service initialization

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-10-16 09:38:57 +03:00
a59aae760f metadata: use new helper
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-10-12 17:20:52 +03:00
0a5b34a07b metadata: small optimization and export default metadata size
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-10-12 17:17:59 +03:00
62502ad720 always generate call with CamelCased name
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-10-12 16:19:30 +03:00
6e43ae7190 add client publish option func
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-10-12 12:09:09 +03:00
0e1f744fcc add helper for publish options
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-10-10 00:47:09 +03:00
2fc47782cf use metadata helper
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-10-09 16:51:58 +03:00
34d93306d6 new registry util func
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-10-09 16:49:29 +03:00
336868ed0d move helper to proper place
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-10-09 16:21:47 +03:00
2682f15b8e move helper to proper place
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-10-09 16:20:10 +03:00
4c12e38c01 move generic code from grpc server implementation
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-10-09 16:15:36 +03:00
62bfe9c06e allow to publish message via broker on noop client
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-10-09 13:43:04 +03:00
24be220f91 close micro-roadmap/issues/12
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-10-09 12:15:55 +03:00
cacd33e84f metadata: fix tests
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-10-01 16:05:05 +03:00
9475003059 fix concurrent map usage
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-10-01 16:00:01 +03:00
8532ccebba metadata: avoid allocations on delete
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-09-30 16:21:47 +03:00
9c55b1d06a fix metadata issues with uppercase letters
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-09-30 16:14:54 +03:00
efd9075d9b add error vars
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-09-28 13:08:53 +03:00
4c4fa00a5d add useful func
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-09-22 13:33:57 +03:00
21d5ca1cdd rename func
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-09-22 13:17:38 +03:00
ec3c1a02fc expose useful broker and server methods
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-09-22 13:15:05 +03:00
dc5dc6ab5b update
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-09-20 17:02:41 +03:00
1cbd1d2bad fix
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-09-20 16:57:54 +03:00
aa667728a1 move transport
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-09-20 16:52:26 +03:00
9b11ea527a add Wait option
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-09-20 15:48:07 +03:00
5787a1afb8 more useful router new options func
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-09-17 15:44:35 +03:00
74c10f1139 more idiomatic names inside generated protoc files
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-09-17 15:44:05 +03:00
7e3fac8937 fix store context issues
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-09-17 15:41:49 +03:00
6021edc855 add more context to store
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-09-17 15:18:01 +03:00
8817c110d0 add context to store
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-09-17 15:15:42 +03:00
d59db9df16 check for nil cmd
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-09-14 12:58:51 +03:00
2d1e6db9fd add context in server handler option
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-09-11 11:55:31 +03:00
5bfca99627 fix old proto
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-09-10 15:17:23 +03:00
9ea3149b60 fixup opts
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-09-10 00:25:33 +03:00
8f03480ed2 update go.mod
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-09-10 00:08:59 +03:00
caec730248 move out tracers
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-09-10 00:06:29 +03:00
f1fde75567 fix init
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-09-07 15:29:43 +03:00
5fe3a46732 init default stuff
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-09-07 13:38:52 +03:00
e7d418183b fixup logger usage (#33)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-09-05 02:43:16 +03:00
c576749b57 noop impl (#32)
* improve logger usage
* add noop client and server

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-09-05 02:11:29 +03:00
c062aab1a9 add noop broker and noop store (#30)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-09-03 15:11:05 +03:00
0252addf05 broker: resurrect DisableAutoAck
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-31 16:51:58 +03:00
b7338c12d7 broker: resurrect Queue option
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-31 16:48:29 +03:00
7c115823a7 Revert "fix protoc-gen-micro"
This reverts commit 47d007c0b6.
2020-08-31 11:51:30 +03:00
47d007c0b6 fix protoc-gen-micro
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-31 10:52:19 +03:00
c9b283be60 move out cache implementations
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-31 10:51:58 +03:00
112f21006c config: add default config
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-29 18:08:21 +03:00
53654185ba add logger to options
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-29 17:44:49 +03:00
2382446e10 registry: set noop as default registry
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-29 17:44:04 +03:00
24c20b6907 resolver/registry: small slice optimization
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-29 17:43:36 +03:00
622490fbf3 logger: refactor interface
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-29 17:43:06 +03:00
dd8894e673 registry: add noop registry
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-29 17:41:49 +03:00
eb1b14da8a model: split options, add logger
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-29 17:40:25 +03:00
0005f23585 errors: move grpc error def to grpc server
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-29 17:32:57 +03:00
fb233374a0 resolver/dns: support ipv6 addrs
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-29 16:53:53 +03:00
9c695ac343 split router implementations
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-28 12:19:47 +03:00
2c136b005e resurrect default for auth
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-28 11:55:18 +03:00
7cf42589b3 cleanup deps
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-28 11:52:51 +03:00
6aa857dfa1 fixup deps
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-28 11:27:45 +03:00
0f19355621 resurrect service stuff
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-28 10:58:08 +03:00
aa99378adc add check (#27)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-27 11:32:27 +03:00
b4ccde2228 resurrect broker event (#26)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-27 11:18:02 +03:00
36c53b4917 сleanup (#24)
* move out prometheus metrics
* not use gorilla wrappers

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-25 17:59:41 +03:00
ef773d8d49 remove util/log in favour of logger (#23)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-25 17:31:28 +03:00
fc3794f548 move runtime implementations (#22)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-25 15:55:30 +03:00
67ab44593b fix repocard issues (#21)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-25 15:41:48 +03:00
8076e410a9 fix repocard issues (#20)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-25 14:33:36 +03:00
dd78ae8658 cleanup (#18)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-25 14:16:08 +03:00
0f4b1435d9 move implementations to external repos (#17)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-25 13:44:41 +03:00
c4a303190a lint fixes (#14)
* lint fixes

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-21 14:53:21 +03:00
199ff66bd4 enable cache for build, closes #8 (#12)
* enable cache for build, closes #8
* goimports
* lint fixes

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-20 15:23:41 +03:00
98ba3b2788 grpc: avoid allocations for each message (#11)
* grpc: avoid allocations for each message
* fix tests for api/router

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-20 14:45:47 +03:00
5ea2590891 Merge pull request #10 from unistack-org/quic
update quic go package
2020-08-20 14:29:45 +03:00
0a42845a40 fix tests
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-20 14:20:27 +03:00
Asim Aslam
e6daa9a838 Update debug.go 2020-08-20 14:20:27 +03:00
ben-toogood
72621e0da4 events: update interface (#1954) 2020-08-20 14:20:27 +03:00
Dominic Wong
d5da9c0728 Unify the store tests (#1952)
Add more tests for store
2020-08-20 14:20:12 +03:00
Janos Dobronszki
eee5b98d78 Generic git checkout (#1951) 2020-08-20 14:18:53 +03:00
ben-toogood
cf084b410f util/file: allow context to be passed (#1950) 2020-08-20 14:18:52 +03:00
cf9bdd0f99 update quic go package
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-20 12:37:40 +03:00
06136312bb regen files with never protoc (#6)
* regen files with never protoc
* rewrite import path

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-19 17:47:17 +03:00
7a407d5792 setup lint (#3)
* setup lint

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-19 16:11:03 +03:00
ben-toogood
66df1bb361 events/nats: add support for TLS config (#1946)
* events/nats: add support for TLS config

* events/nats: improve error logging
2020-08-19 10:55:54 +01:00
Asim Aslam
7eaec450a1 support error handler in memory broker (#1947) 2020-08-19 10:20:43 +01:00
Asim Aslam
5d6b7b3d7d Move the network resolver out (#1944) 2020-08-18 21:38:29 +01:00
Dominic Wong
2eac8ed64f Fix cockroach store not respecting WriteTTL option (#1943)
* cockroach fixes for expiry

* cockroach should run in the background
2020-08-18 18:30:05 +01:00
Janos Dobronszki
2b2dc2f811 Support private repos in env 'local' (#1938) 2020-08-18 18:26:14 +02:00
ben-toogood
21cca297c0 events: implement package with memory & nats streams (#1942) 2020-08-18 16:19:53 +01:00
Asim Aslam
19ef225b2f Revert "grpc: avoid allocations for each message (#1939)" (#1941)
This reverts commit 2a23224d91.
2020-08-18 14:44:29 +01:00
2a23224d91 grpc: avoid allocations for each message (#1939)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-18 14:24:11 +01:00
Asim Aslam
dd2dc7a2b9 Update broker.go 2020-08-18 14:05:25 +01:00
Asim Aslam
4413372a3f Decruft the broker by removing Event interface (#1940) 2020-08-18 14:00:51 +01:00
Janos Dobronszki
a2a808f2d6 Baseurl, gitlab support, single word service names (#1933) 2020-08-18 11:31:49 +02:00
Asim Aslam
7a6669d199 Update reporter.go 2020-08-18 08:30:29 +01:00
Asim Aslam
09fdd3c121 Update reporter.go 2020-08-18 08:29:26 +01:00
Prawn
da4159513e Metrics interface and Prometheus implementation (#1929)
* Metrics interface

* Prometheus implementation

* NoOp implementation

Co-authored-by: chris <chris@Profanity.local>
2020-08-18 08:27:50 +01:00
Asim Aslam
e1248f90f4 update options 2020-08-17 23:09:41 +01:00
Asim Aslam
3011bad518 sort routes by metric 2020-08-17 23:09:24 +01:00
Asim Aslam
bb7fe21c46 unused variables 2020-08-17 23:00:27 +01:00
Asim Aslam
4fd4a116f2 allow setting registry router in client 2020-08-17 22:53:20 +01:00
Asim Aslam
50ec6c748f cleanup client/selector/lookup (#1937)
* cleanup client/selector/lookup

* add mdns router, remove registry from client

* fix roundtripper

* remove comment

* fix compile issue

* fix mucp test

* fix api router
2020-08-17 22:44:45 +01:00
Asim Aslam
7135787b78 Update README.md 2020-08-17 19:43:28 +01:00
Asim Aslam
870a1ebc07 dead code 2020-08-17 10:04:52 +01:00
zuoan
61899398b3 simplifies code (#1934)
Co-authored-by: 刘海洋 <haiyang@snqu.com>
2020-08-17 11:10:42 +03:00
Asim Aslam
55d62fc1a5 Strip Advertise/Process from router 2020-08-14 23:51:52 +01:00
Asim Aslam
5238a8a85f don't delete own routes 2020-08-14 23:04:55 +01:00
Asim Aslam
9fffd0419e Merge branch 'master' of ssh://github.com/micro/go-micro 2020-08-14 21:52:18 +01:00
Asim Aslam
58794df27c default to noop registry in network 2020-08-14 21:52:05 +01:00
ben-toogood
5a88ea7247 runtime: resource limits (kubernetes implementation) (#1931)
* runtime: add resource limit CreateOptions

* util/kubernetes/client: implement support for resource limits

* runtime/kubernetes: set resource limits for k8s deployments

* util/kubernetes: remove template check for ints

* util/kubernetes: fix incorrect yaml syntax

* runtime/kubernetes: fix incorrect units

* runtime: update create options to use Resources struct
2020-08-14 11:47:28 +01:00
Asim Aslam
374aae1490 Merge branch 'master' of ssh://github.com/micro/go-micro 2020-08-13 14:10:49 +01:00
Asim Aslam
ccf2f4efd6 fix windows 2020-08-13 14:10:41 +01:00
ben-toogood
9380b365de runtime/local: fix injection of secrets as env vars (#1930) 2020-08-13 09:22:25 +01:00
Asim Aslam
f0142febcf executable is now os 2020-08-13 07:57:57 +01:00
Asim Aslam
1fa3ac5599 write nil when expiry is zero 2020-08-12 12:52:14 +01:00
Asim Aslam
375b67ee16 simplify runtime logs 2020-08-11 22:57:30 +01:00
Dominic Wong
69a53e8070 expiry can be taken from options or record (#1928) 2020-08-11 18:11:18 +01:00
Asim Aslam
b6e1c7ac99 make source dir a variable 2020-08-11 17:25:43 +01:00
Asim Aslam
e83a808b05 make log dir a variable 2020-08-11 17:23:00 +01:00
ben-toogood
012ec6a998 router/registry: fix expiring routes bug (#1927) 2020-08-11 16:57:04 +01:00
Asim Aslam
fae4151027 Add a build package (#1926)
* Add a build package

* fix go mod

* package tar
2020-08-11 16:51:58 +01:00
ben-toogood
e162e6d505 router/registry: fix bug which impacts service registered in multiple domains (#1925)
* router/registry: fix bug which impacts service registered in multiple domains

* router/registry: bugfix
2020-08-11 12:42:22 +01:00
Asim Aslam
c51ef6fc29 move wrapper to client 2020-08-11 11:25:49 +01:00
Asim Aslam
28d6340f04 Merge branch 'master' of ssh://github.com/micro/go-micro 2020-08-11 10:32:25 +01:00
Asim Aslam
4fc193f95d Delete the cmd package 2020-08-11 10:24:55 +01:00
Asim Aslam
d072eb6ff2 Deprecate service (#1924) 2020-08-11 10:03:47 +01:00
ben-toogood
1263806a39 util/kubernetes: add readiness check to deployments (#1923) 2020-08-11 08:38:30 +01:00
Asim Aslam
959407bad9 support wrapper slice in api server options 2020-08-10 22:38:54 +01:00
Asim Aslam
61d12d3a39 fix etcd keys for services (#1922) 2020-08-10 21:58:35 +01:00
Asim Aslam
4db8ea8f6a Move tunnel to its own package (#1921) 2020-08-10 17:31:21 +01:00
Asim Aslam
13f495587e cleanup debug and transport (#1920) 2020-08-10 15:58:39 +01:00
ben-toogood
593b543230 runtime/kubernetes: fix streaming logs error handling (#1919) 2020-08-10 15:20:33 +01:00
ben-toogood
fdce953c15 runtime/kubernetes: fix update bug (#1918) 2020-08-10 15:08:04 +01:00
Janos Dobronszki
96836f2e43 Decrease log levels in router/registry package to not appear for CLI users (#1917) 2020-08-10 13:57:45 +01:00
Asim Aslam
65e6ee8566 use noop resolver in network by default 2020-08-09 22:11:57 +01:00
Asim Aslam
a7c70c66b1 return a micro error on lookup failure 2020-08-09 21:44:39 +01:00
Asim Aslam
b2582c0992 fix deadlock bug 2020-08-09 19:39:21 +01:00
Asim Aslam
6373cc91b7 remove print statement 2020-08-09 19:35:07 +01:00
Asim Aslam
ed704640aa getDomain should return the default domain 2020-08-09 19:08:25 +01:00
Asim Aslam
cd9e5a1e9e continue to allow endpoint routing 2020-08-09 16:57:34 +01:00
Asim Aslam
dcf040ec9f strip back the grpc proxy 2020-08-09 16:47:00 +01:00
Asim Aslam
f838c33008 noop.NewRegistry function 2020-08-09 16:26:51 +01:00
Asim Aslam
e8ea0f85e9 add a noop registry 2020-08-09 16:17:52 +01:00
Asim Aslam
51f8b4ae3d embed grpc server stream and client so they can be accessed (#1916) 2020-08-09 15:43:41 +01:00
Asim Aslam
69a2032dd7 lower log level to debug 2020-08-08 14:04:18 +01:00
Asim Aslam
64feb6dff2 Add subscriber naem 2020-08-08 09:21:13 +01:00
Asim Aslam
4c95c65d81 Return service name in error 2020-08-08 09:09:34 +01:00
Asim Aslam
4469a41ae7 use a totally different client for the watcher in etcd 2020-08-08 01:40:41 +01:00
Asim Aslam
fc67593ee4 cleanup router watcher logic 2020-08-08 01:04:38 +01:00
Asim Aslam
e7cc3c2210 protect etcd watcher stop against race condition 2020-08-08 00:57:57 +01:00
Asim Aslam
712fe39a62 initChan is never evaluated because watchRegistry is a blocking call 2020-08-07 23:44:43 +01:00
Asim Aslam
9b14eb8aec close the existing etcd client if it exists 2020-08-07 23:09:06 +01:00
Asim Aslam
124b1bd7b7 add https prefix when using tls config for etcd 2020-08-07 22:46:05 +01:00
ben-toogood
ac1aace214 route the API subdomain (#1910)
Co-authored-by: Asim Aslam <asim@aslam.me>
2020-08-07 20:54:55 +01:00
Asim Aslam
324c4e6886 Router refresh (#1912)
* checkpoint

* Refresh and prune routes periodically in the registry router

* remove comment
2020-08-07 20:53:38 +01:00
Asim Aslam
d69a4a30cd fix etcd bug that causes deregister to be skipped (#1911) 2020-08-07 19:58:25 +01:00
Asim Aslam
a6d7b1d710 Move api/router/util to util/router (#1909) 2020-08-07 13:30:29 +01:00
Asim Aslam
8ee31b94a1 remove handler/util package in favour of util/router (#1908) 2020-08-07 12:47:20 +01:00
Asim Aslam
37cc7fda92 Update pprof.go 2020-08-07 12:18:01 +01:00
Asim Aslam
d61cbd29db Update README.md 2020-08-07 11:22:57 +01:00
Asim Aslam
b6ab124d83 Update README.md 2020-08-07 11:21:59 +01:00
Dominic Wong
835343d6a5 logs should return for non existent services (#1906) 2020-08-06 22:56:05 +01:00
Maarten Bezemer
74907987d1 codec - Allow to Write() nil body (#1905)
* codec - Allow to Write() nil body

* Oops we are in v3 now
2020-08-06 18:51:00 +01:00
Asim Aslam
fb8533b74e Update tunnel 2020-08-06 18:50:35 +01:00
Z
dcf785677f Fix: file-watcher bugs (#1897)
* Fix: file-watcher bugs

* Update watcher_linux.go

Co-authored-by: 杨铭哲 <yangmz@weipaitang.com>
Co-authored-by: Asim Aslam <asim@aslam.me>
2020-08-06 18:21:09 +01:00
ben-toogood
991cdba91d registry/etcd: fix services combining (#1901) 2020-08-06 15:38:50 +01:00
Asim Aslam
aefd052dd7 Etcd router bug fixing etcd path prefix matching name (#1899)
* add logging and don't get nodes where they exist in router

* add more logging

* Fix the etcd bug for name matching of keys and prefixes matching names
2020-08-06 12:42:14 +01:00
Asim Aslam
2b79910ad9 add logging and don't get nodes where they exist in router (#1898)
* add logging and don't get nodes where they exist in router

* add more logging
2020-08-06 11:32:06 +01:00
Asim Aslam
8674dc8e62 Remove precache in favour of just pulling by default 2020-08-06 10:27:58 +01:00
Asim Aslam
b93cd0c964 dont process endpoint unless absolutely necessary 2020-08-05 18:09:04 +01:00
Asim Aslam
39bd6a6ced skip watching routes if client proxy is set, remove later 2020-08-05 18:05:25 +01:00
Asim Aslam
03d47afe47 Fix proxy selector memory leak 2020-08-05 17:38:41 +01:00
ben-toogood
38ec233350 proxy/mucp: don't lookup routes if client using proxy (#1896) 2020-08-05 12:45:56 +01:00
Dominic Wong
eee91ed976 Check chan not closed before sending updates for memory loader (#1894)
* dont send on closed chan
2020-08-04 16:21:03 +01:00
ben-toogood
07fef9fd33 router/registry: fix initialization bug (#1893) 2020-08-04 11:43:01 +01:00
Asim Aslam
1106f1d996 remove agent 2020-08-04 07:51:10 +01:00
Asim Aslam
8e126e4fc1 Remove go-micro/web 2020-08-04 07:47:20 +01:00
Asim Aslam
1439b101ec ensure register ttl and interval are set 2020-08-03 22:44:29 +01:00
Asim Aslam
24e5b2a034 Merge branch 'master' of ssh://github.com/micro/go-micro 2020-08-03 22:21:13 +01:00
Asim Aslam
971a962894 Fix typo 2020-08-03 22:20:30 +01:00
ben-toogood
31ed4aa0e8 registry/etcd: fix logging nil pointer dereference (#1889)
* registry/etcd: fix logging nil pointer dereference

* Fix stupid mistake

* Fix merge
2020-07-31 15:05:32 +01:00
ben-toogood
d2cea4b7b7 registry/etcd: fix logging nil pointer dereference (#1888) 2020-07-31 14:40:11 +01:00
ben-toogood
0b73d411ad client: rename WithServiceToken => WithAuthToken (#1887) 2020-07-31 11:36:33 +01:00
ben-toogood
83a64797fb Fix proxy being overriden by default addresses (#1886) 2020-07-31 08:55:08 +01:00
ben-toogood
e9fc5b1671 client: add proxy option (#1885)
* client: add proxy option

* client: add WithProxy CallOption

* use address option

* ProxyAddress => Proxy
2020-07-30 15:22:36 +01:00
ben-toogood
006bbefaf3 runtime: support for dynamic secrets (#1861)
* runtime: replace CreateCredentials with CreateSecret

* runtime/kubernetes: secrets support

* runtime: CreateSecret => WithSecret

* runtime: use map[string]string for secrets

* runtime/kubernetes: update to use kv secrets

* Fix merge conflict (missing import)

Co-authored-by: Asim Aslam <asim@aslam.me>
2020-07-29 13:41:50 +01:00
Lars Lehtonen
3d1ba914fc tunnel: remove unused test loop (#1878)
Co-authored-by: Asim Aslam <asim@aslam.me>
2020-07-29 12:51:09 +01:00
yu
d66803a136 fix bug https://github.com/micro/go-micro/issues/1883 (#1884)
* fix #1883

* fix #1883

Co-authored-by: 杨羽 <yangyu@doumi.com>
2020-07-29 12:45:25 +01:00
ben-toogood
9813f98c8b config: remove default config (#1882)
Co-authored-by: Asim Aslam <asim@aslam.me>
2020-07-28 13:54:58 +01:00
c6163bb22f fix qson parsing on invalid input, close #1874 (#1880)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-07-28 12:34:50 +01:00
ben-toogood
cb4a2864da router/registry: fix not started bug (#1877) 2020-07-28 09:01:08 +01:00
Asim Aslam
f17e4fdb44 Update README.md (#1876) 2020-07-27 16:42:50 +01:00
Asim Aslam
563768b58a v3 refactor (#1868)
* Move to v3

Co-authored-by: Ben Toogood <bentoogood@gmail.com>
2020-07-27 13:22:00 +01:00
Dominic Wong
9dfeb98111 cockroach typo in init (#1872) 2020-07-27 10:16:40 +01:00
Asim Aslam
5f4491bb86 change network resolver http to localhost:8080 2020-07-26 11:21:57 +01:00
Janos Dobronszki
fbdf1f2c1c Fixing micro logs being follow by default against k8s (#1866) 2020-07-23 09:50:38 +02:00
ben-toogood
a3a7434f2c client/grpc: fix error panic (#1860) 2020-07-20 10:04:51 +01:00
Asim Aslam
592179c0a2 Remove deprecations since next release is v3 2020-07-19 19:59:33 +01:00
Asim Aslam
9b74bc52d6 Move defaults to defaults.go 2020-07-19 19:48:11 +01:00
Asim Aslam
05f3e1a125 Add cmd.Run function 2020-07-19 18:43:33 +01:00
Asim Aslam
16c591d741 call cmd.Run 2020-07-19 18:20:17 +01:00
Asim Aslam
755b816086 Use Run instead of Init for cmd 2020-07-19 18:14:18 +01:00
Asim Aslam
7aa92fa8b5 add String method to command 2020-07-19 17:20:05 +01:00
ijayer
5077683b70 refactor(logger): fix the name of defaultLogger receiver (#1859)
Closes #1858

Co-authored-by: Asim Aslam <asim@aslam.me>
2020-07-19 16:55:50 +01:00
Asim Aslam
7f6cefd9c9 fix grpc test 2020-07-19 15:54:33 +01:00
Asim Aslam
647ce61dec some renaming of types in auth 2020-07-19 14:41:31 +01:00
Asim Aslam
d3326efd4b Move out the token package to util 2020-07-19 13:41:23 +01:00
Asim Aslam
6920677f1e Move rules.Verify to auth.VerifyAccess 2020-07-19 13:12:03 +01:00
Asim Aslam
1838e4a1ee remove auth provider 2020-07-19 11:37:40 +01:00
Asim Aslam
96233b2d9b auth jwt / service package comments 2020-07-19 10:53:38 +01:00
Asim Aslam
e082ac42a0 go fmt 2020-07-19 10:51:16 +01:00
Asim Aslam
d7ef224447 add selector package comment 2020-07-19 10:51:04 +01:00
Asim Aslam
8c6f4062ef Remove error proto in favour of go type 2020-07-19 09:29:48 +01:00
ben-toogood
0d860c53a6 runtime/kubernetes: ignore namespace already exists errors (#1852)
Co-authored-by: Asim Aslam <asim@aslam.me>
2020-07-18 11:12:05 +01:00
bcc890e47c router: pass node metadata to route instead of service metadata (#1855)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-07-17 16:45:22 +01:00
Di Wu
f9bf562393 fix typo in comments (#1840)
* remove global error tracking

* rpc_server: fix invalid register err

* fix typo

Co-authored-by: Asim Aslam <asim@aslam.me>
2020-07-16 16:33:11 +01:00
dfa50a888d make LookupRoute exported (#1850)
* make LookupRoute exported

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* add missing file

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-07-16 16:32:37 +01:00
Asim Aslam
e63b9015ae Add memcache implementation of cache (#1848) 2020-07-16 14:13:38 +01:00
3627e47f04 client/grpc: dont use codec for raw bytes payload (#1847)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-07-16 13:35:06 +01:00
Asim Aslam
7d41c2224e Don't close the stream (#1844) 2020-07-15 14:44:31 +01:00
ben-toogood
68927e875b store/service: use client passed in Init options (#1843) 2020-07-15 14:01:33 +01:00
ben-toogood
0c19a87c89 cmd/cmd: use service namespace as store database (#1842) 2020-07-15 11:31:42 +01:00
ben-toogood
f73ec65ac3 runtime/kubernetes: increase debugging (#1841) 2020-07-15 09:26:25 +01:00
Asim Aslam
b27e71ae64 rip out cmd.DefaultOptions 2020-07-14 22:23:54 +01:00
Asim Aslam
0299517f0d remove config readme 2020-07-14 21:55:05 +01:00
Asim Aslam
e1404a1100 remove secrets package 2020-07-14 21:53:43 +01:00
Asim Aslam
057d61063f Move back command 2020-07-14 20:57:13 +01:00
ben-toogood
73a3f596e8 util/kubernetes/client: set imagePullPolicy to always (#1838) 2020-07-14 15:17:23 +01:00
ben-toogood
0287ab8751 auth/service/proto: add Delete RPC (#1836)
Co-authored-by: Asim Aslam <asim@aslam.me>
2020-07-14 13:41:35 +01:00
Alex Unger
42c28f2b6d Fix Comments (#1833)
* update store url

* fix leftover copy paste
2020-07-14 13:13:32 +01:00
ben-toogood
a2bb0bea2d auth: add token issuer option (#1835) 2020-07-14 13:44:51 +02:00
ben-toogood
9f9c748f9b auth/service: fix account issuer bug (#1834) 2020-07-14 12:16:52 +01:00
ben-toogood
a5e9dc21ca util/wrapper: allow enforcing a specific namespace when verifying requests (#1832)
* auth/jwt: add debugging

* auth: more debugging

* auth: more debugging

* util/wrapper: don't use request context

* util/wrapper: AuthHandlerNamespace

* remove debugging
2020-07-14 10:27:15 +01:00
Janos Dobronszki
3f4b58b58c Let bolt do locking per each List Get etc op, instead of managing fil… (#1831) 2020-07-14 10:35:46 +02:00
Asim Aslam
0a79db498c do not compare snapshot unless non nil (#1830) 2020-07-14 07:52:45 +01:00
Dominic Wong
7c5e3b0f30 report errors from log streaming (#1828) 2020-07-13 17:35:23 +01:00
ben-toogood
07fbb06ed8 auth/service: fix jwt blank refresh bug (#1827) 2020-07-13 17:12:03 +01:00
ben-toogood
a4252ba69c router/registry: use warn error level (#1826) 2020-07-13 15:27:14 +01:00
ben-toogood
8fe4f1f2c3 config/cmd: don't fatally error if config can't be loaded (#1825)
* config/cmd: don't fatally error if config cannot be loaded

* config/cmd: fix log level typo
2020-07-13 15:08:53 +01:00
ben-toogood
2e04fcd718 config/cmd: don't fatally error if auth account cannot be generated (#1824) 2020-07-13 12:52:54 +01:00
ben-toogood
7355455020 auth/service: generate accounts client side if JWT credentials present (#1823) 2020-07-13 10:20:31 +01:00
Lars Lehtonen
040577fb74 transport/grpc: replace deprecated grpc.WithTimeout() (#1822) 2020-07-13 07:35:53 +01:00
ben-toogood
4e7621da18 config/cmd: standardise error handling (#1816)
* runtime/kubernetes: remove reference to runtime cells

* config/cmd: standardize error handling

Co-authored-by: Asim Aslam <asim@aslam.me>
2020-07-12 07:22:08 +01:00
Huan Huang
8e30ede8c7 track error (#1815)
* track error

* remove useless code

Co-authored-by: huanghuan.27@bytedance.com <huanghuan.27@bytedance.com>
Co-authored-by: Asim Aslam <asim@aslam.me>
2020-07-12 07:17:56 +01:00
Asim Aslam
630ceb5dad Update README.md (#1820) 2020-07-11 22:18:53 +01:00
Asim Aslam
85ae232936 Add model to service (#1819) 2020-07-11 21:15:59 +01:00
ben-toogood
13ea0eec02 :registry/mdns: fix nil pointer bug (#1818) 2020-07-10 17:47:07 +01:00
ben-toogood
09ec20fded runtime: provide credentials to services (#1817)
* runtime: inject credentials into service

* util/auth: self generate accounts (needed for jwt)

* runtime/kubernetes: add logging for creds

* runtime/kubernetes: serialize secret name

* runtime/kubernetes: remove unused code

* runtime/kubernetes: base64 encode secret

* runtime/kubernetes: remove metadata from secret

* util/kubernetes/client: omit empty secret metadata

* util/kubernetes/client: fix secret template

* util/kubernetes/client: fix secrets

* web: update auth util

* util/auth: fix missing arg

* extend token expiry

* extend token expiry
2020-07-10 16:25:46 +01:00
ben-toogood
3480e0a64e runtime/kubernetes: remove reference to runtime cells (#1814) 2020-07-09 20:21:34 +01:00
ben-toogood
318a80f824 config/cmd: improve cert loading for infra (#1813)
* config/cmd: improve cert loading for infra

* config/cmd: remove certificate_authorities flag

* config/cmd: fix caps

* config/cmd: fix bug with IsSet

* config/cmd: fix bool flags
2020-07-09 18:02:24 +01:00
ben-toogood
6d9a38a747 kubernetes: fixes for production (#1812)
* util/kubernetes/client: add secrets to deployments

* util/kubernetes/client: remove ServiceAccountName override

* debugging

* runtime/kubernetes: fix error

* runtime/kubernetes: remove test secret

* util/kubernetes/client: update default image

* util/kubernetes/client: remove default command for deployments

* runtime/kubernetes: pass source as arg

* runtime/kubernetes: remove debugging

* util/kubernetes/client: revert default image change
2020-07-09 16:29:01 +01:00
Asim Aslam
58d6726380 The start of mud - the micro data model (#1811)
* The start of mud - the micro data model

* add comments
2020-07-09 12:11:32 +01:00
Huan Huang
e5db6ea8a7 close r/w (#1810)
Co-authored-by: huanghuan.27@bytedance.com <huanghuan.27@bytedance.com>
2020-07-09 10:28:20 +01:00
Huan Huang
3468331506 feat: refactor register func (#1807)
Co-authored-by: huanghuan.27@bytedance.com <huanghuan.27@bytedance.com>
Co-authored-by: Asim Aslam <asim@aslam.me>
2020-07-08 18:38:01 +01:00
王旭
1bac08cc0e server.Init(Wait(nil)) update server options context (#1804)
Co-authored-by: wangxu <wangxu@oneniceapp.com>
Co-authored-by: Asim Aslam <asim@aslam.me>
2020-07-08 18:36:07 +01:00
ben-toogood
333320dcb8 config/cmd: secure broker (#1806)
* config/cmd: secure broker

* config/cmd: remove testing
2020-07-08 16:22:48 +01:00
Asim Aslam
ce12c040fa Model updates 2020-07-08 15:09:18 +01:00
Asim Aslam
ee36e26edc Add model interface (#1808) 2020-07-08 14:57:45 +01:00
Asim Aslam
3ffb899951 Fix cache options 2020-07-08 14:53:38 +01:00
Asim Aslam
00bd2bc65f cache interface (#1805) 2020-07-08 11:08:59 +01:00
ben-toogood
86f4235aaf config/cmd: custom certificate authorities & secure registry (#1803)
* config/cmd: add registry_secure option

* config/cmd: tmp load ca

* config/cmd: tmp load ca

* config/cmd: refactor certificate_authorities setup

* config/cmd: improve usage
2020-07-08 08:50:08 +01:00
Di Wu
b37f9c94b8 Fix invalid register check err in log (#1801)
* remove global error tracking

* rpc_server: fix invalid register err

Co-authored-by: Asim Aslam <asim@aslam.me>
2020-07-07 14:14:23 +01:00
Asim Aslam
0ed1c70d29 Update README.md 2020-07-07 13:34:42 +01:00
Asim Aslam
db8e10834b Update README.md (#1802) 2020-07-07 13:33:54 +01:00
ben-toogood
0a937745cd auth: pass namespace options in auth service requests (#1800)
* auth: pass namespace options in auth service requests

* auth/service/proto: update field index

Co-authored-by: Asim Aslam <asim@aslam.me>
2020-07-07 08:30:25 +01:00
ben-toogood
f5ed7e5833 config/source/service: change default namespace to micro (#1798)
Co-authored-by: Asim Aslam <asim@aslam.me>
2020-07-07 08:19:52 +01:00
Metauro
859b9e7786 feat(errors): add gateway, service error (#1797) 2020-07-06 20:14:59 +01:00
Lars Lehtonen
2b033b6495 store/cockroach: fix dropped errors (#1796)
Co-authored-by: Asim Aslam <asim@aslam.me>
2020-07-06 20:14:36 +01:00
Di Wu
51caf2a24e remove global error tracking (#1777)
Co-authored-by: Asim Aslam <asim@aslam.me>
2020-07-06 20:14:22 +01:00
Enix Yu
eaa46c2de7 Add recover in grpc service handler (#1727)
* 🐛 bug(grpc): add missing recover in grpc unkonwn service handler

* Add grpc handler recover testcases

* improve test case

Co-authored-by: ben-toogood <bentoogood@gmail.com>
Co-authored-by: Asim Aslam <asim@aslam.me>
2020-07-06 20:13:51 +01:00
Colin Hoglund
90dca65f55 make environment variable interpolation preprocessor optional (#1715) 2020-07-06 20:13:35 +01:00
97ae2979ad pass request context from request rpc endpoints (#1799)
http middleware can add additional metadata to context,
for example tracing wrappers, pass down it to underlining
services

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-07-06 13:55:17 +01:00
Asim Aslam
6f309dada3 fix typo (#1789) 2020-07-06 13:52:42 +01:00
Huan Huang
f99b436ec2 feat: fix register bug (#1791) 2020-07-03 14:38:25 +01:00
ben-toogood
c817f29d6e router/registry: fix registry not found bug (#1794) 2020-07-03 13:35:59 +01:00
ben-toogood
f744c6248f runtime/service: pass namespace option to service (#1792) 2020-07-03 11:37:14 +01:00
ben-toogood
4ff114e798 router/registry: fix rlock bug when registry errors (#1788)
* client: add select options

* router/registry: fix rlock bug when registry errors

* Revert "client: add select options"

This reverts commit 4d5283452e183f7387b604b51bde1deaf87ee391.

* router/registry: findRoutes under rlock

* add test

Co-authored-by: Dominic Wong <dom@micro.mu>
2020-07-02 18:29:11 +01:00
ben-toogood
c58ac35dfc broker/service: use wrapped micro client to authenticate requests (#1782) 2020-07-02 17:54:53 +01:00
ben-toogood
b5314829fa client/{grpc,rpc}: fix previous breaking change with CallFunc (router.Route vs registry.Node) (#1781) 2020-07-02 17:26:45 +01:00
ben-toogood
41c7688697 options: add router option (#1783)
* broker/service: use wrapped micro client to authenticate requests

* options: add router option

* Revert "broker/service: use wrapped micro client to authenticate requests"

This reverts commit f2383f37c86467b4ce534313a7f59993a904a712.
2020-07-02 17:17:07 +01:00
ben-toogood
b021546c09 client: add select options (#1786) 2020-07-02 17:03:08 +01:00
ben-toogood
6898a65508 selector: add filters to replace depricated client/selector filters (#1785) 2020-07-02 16:09:48 +01:00
ben-toogood
d577dd6abe config: add namespace support (#1780)
* config/cmd: use service namespace for config

* config/service: add namespace option to list
2020-07-02 14:07:58 +01:00
Janos Dobronszki
3c633e3577 Sparse checkout of repos, all repo downloads happen to different folders for concurrency support (#1779) 2020-07-02 14:40:40 +02:00
ben-toogood
174e44b846 Deprecate client/selector (#1767)
* client/{grpc,rpc}: depricate selector (wip)

* {client,cmd}: remove client/selector

* deprecate client/selector

* router/static: fix lookup

* config/cmd: add support for legacy static selector flag

* config/cmd: add support for legacy dns selector flag
2020-07-01 17:06:59 +01:00
Dominic Wong
a63480a81a router/registry: fix fallback fails if service has been seen already (#1776) 2020-07-01 15:20:30 +01:00
ben-toogood
6d9d94b105 api/router/registry: use resolved domain (#1774) 2020-07-01 12:23:55 +01:00
ben-toogood
64e9185386 router/registry: fix nil eventChan bug (#1773)
* router/registry: fix nil eventChan bug
2020-07-01 12:03:13 +01:00
ben-toogood
1b5c83f3cc registry/mdns: fix deregister bug (#1771)
* registry/mdns: fix deregister bug

* Update registry/mdns_registry.go

Co-authored-by: Dominic Wong <domwongemail@googlemail.com>
2020-07-01 11:09:20 +01:00
ben-toogood
979af853b9 proxy/mucp: use Micro-Namespace to filter networks (#1772) 2020-07-01 10:55:46 +01:00
ben-toogood
a64078b5c3 router/service: handle not found error (#1770) 2020-07-01 10:18:19 +01:00
Dominic Wong
58845d7012 only prewarm the route table if requested (#1765) 2020-07-01 10:05:21 +01:00
ben-toogood
dcf01ebbf0 router/registry: fix concurrent map iteration and map write (#1762) 2020-06-30 17:40:38 +01:00
Dominic Wong
355ad2a1af push tags to docker hub (#1766) 2020-06-30 17:26:59 +01:00
ben-toogood
b882ff3df9 selector: update selector.Select to accept a slice of structs (#1764) 2020-06-30 15:51:26 +01:00
ben-toogood
6337c92cd0 selector: new selector interface with random & roundrobin implementation (#1761)
* selector: implement new selector interface plus random & roundrobin implementations

* selector/roundrobin: remove unused consts

* router: add close method to interface

* selector/roundrobin: fix concurrent map iteration and map write

* selector: replace variadic argument on Select
2020-06-30 14:54:38 +01:00
ben-toogood
a95accad56 router: add metadata to routes (#1763)
* router: add metadata to route

* router/registry: set node metadata in route

* router/service: pass metadata to/from router service
2020-06-30 14:10:13 +01:00
Dominic Wong
6532b6208b MDNS registry fix for users on VPNs (#1759)
* filter out unsolicited responses
* send to local ip in case
* allow ip func to be passed in. add option for sending to 0.0.0.0
2020-06-30 11:12:52 +01:00
ben-toogood
0f5c53b6e4 selector: use custom domain (#1760)
* util/wrapper: improve auth errors

* client: add network call option

* client/selector: add domain select option

* client/grpc: pass network option to selector
2020-06-30 10:07:52 +01:00
ben-toogood
deea8fecf4 router/registry: add fallback if routes aren't found in the cache (#1758)
* router/registry: add fallback if routes aren't found in the cache

* router: fix rlock bug

* router/registry: pass fetchRoutes into the table, not the router
2020-06-30 09:53:49 +01:00
ben-toogood
df3e5364ca api/resolver: add resolve options (#1756)
* api/resolver: Resolve options

* router/registry: fix init bug

* router/registry: fix wildcard query bug

* web: fix registation domain bug

* registry/etcd: pass domain in service metadata

* api/resolver/subdomain: expose domain func

* Update api/resolver/subdomain/subdomain.go

Co-authored-by: Dominic Wong <domwongemail@googlemail.com>

Co-authored-by: Dominic Wong <domwongemail@googlemail.com>
2020-06-29 16:37:45 +01:00
Di Wu
132c1e35fe Fix invalid usage for sync.WaitGroup (#1752)
* Custom private blocks

* Fix invalid usage for sync.WaitGroup

Co-authored-by: Asim Aslam <asim@aslam.me>
2020-06-27 20:07:04 +01:00
Dominic Wong
5967a68e78 cached file store (#1739)
* cached file store
2020-06-26 16:13:53 +01:00
ben-toogood
104b7d8f8d api/resolver: update resolver to enable subdomain routing (#1747)
* api/resolver: update domain / service prefix usage

* api/resolver/subdomain: implement subdomain resolver for domain resolution

* api/handler: fix tests
2020-06-26 14:28:18 +01:00
ben-toogood
4f0f4326df router: improve router configuration (#1745)
* router: update default address to :8084

* service: add router to service options

* config/cmd: improve router setup
2020-06-26 10:38:11 +01:00
ben-toogood
ee02511658 proxy/mucp: add support for multi-tenancy (#1746) 2020-06-26 10:31:06 +01:00
ben-toogood
a8fc5590a8 client/selector: query across multiple domains (#1725)
* client/selector: query across multiple domains

* client/selector: check for nil services

* config/cmd: fix merge bug
2020-06-25 15:40:23 +01:00
ben-toogood
bc60f23ff6 config/cmd: setup registry before router (#1743) 2020-06-25 15:24:31 +01:00
ben-toogood
2000da6fd8 router/registry: add support for registry domains (#1744) 2020-06-25 12:35:00 +01:00
ben-toogood
5ab475636a server/{grpc,rpc}: fix deregister domain bug (#1742)
* server/{grpc,rpc}: fix deregister domain bug

* server/grpc: remove unnecessary slice
2020-06-25 11:25:43 +01:00
ben-toogood
51b4ab0abc registry/memory: watcher bug fixes (#1740)
* registry/memory: watcher bugfixes

* registry/memory: fix nil watcher bug

* registry/memory: fix watcher test
2020-06-25 11:02:35 +01:00
ben-toogood
687a5e2e58 util/wrapper: fix 401 error when requesting the default namespace (#1741) 2020-06-25 10:19:03 +01:00
Dominic Wong
fcd307d902 Build and test forked PRs properly (#1738)
* build forks on PRs properly
2020-06-24 23:41:27 +01:00
ben-toogood
00cd07a3a6 util/wrapper: set auth credentials on streams (#1735) 2020-06-24 16:45:34 +01:00
Dominic Wong
a2a1f4dfbd support mono repo deps (#1736)
* support mono repo deps

* add protoc
2020-06-24 16:27:22 +01:00
ben-toogood
2b506b1a2a auth/service: use address option since router may not be configured (#1734) 2020-06-24 13:47:43 +01:00
ben-toogood
a2550820d3 router: add to service options; add dns and static implementations (#1733)
* config/cmd: add router to service options

* router/service: use micro client
2020-06-24 11:46:51 +01:00
ben-toogood
c940961574 router: update interface (#1732)
* router: replace Start and Stop with Close

* router: update default network to micro

* router: update tests
2020-06-24 11:09:16 +01:00
Dominic Wong
695cc9d526 Build against micro and examples on pull requests (#1724)
* Build against micro and examples on pull requests
2020-06-19 17:19:58 +01:00
ben-toogood
87543b2c8a registry/etcd: add support for domain options (#1714) 2020-06-19 14:58:16 +01:00
ben-toogood
5f9c3a6efd registry/cache: add support for the domain option (#1722) 2020-06-19 13:16:44 +01:00
ben-toogood
2b889087bd config/cmd: fix selector setup bug (#1723) 2020-06-19 13:11:48 +01:00
ben-toogood
ece02a6d21 util/wrapper: fix noop auth nil account bug (#1721)
* util/wrapper: fix noop nil account

* util/wrapper: improve comments

* util/wrapper: update tests
2020-06-19 12:16:39 +01:00
ben-toogood
58c6bbbf6b registry/service: pass domain options via rpc (#1719)
* registry/service: regenerate proto

* registry/service: pass domain in proto request options

* registry/service: stop defaulting metadata

* registry: add default domain const; remove from implementations

* registry/memory: fix typo
2020-06-19 10:34:12 +01:00
ben-toogood
c16f4b741c server: register in the services namespace (#1718) 2020-06-19 09:24:32 +01:00
Colin Hoglund
83cecdb294 config: use configured reader by default (#1717) 2020-06-19 08:49:30 +01:00
ben-toogood
8c7c27c573 registry/memory: add support for domain options (#1713)
* registry/memory: add support for the domain options

* registry/memory: swap Fatal test cases with Error

* registry/memory: fix wildcard not found bug

* registry/memory: replace locks with rlocks

* registry/memory: fix deregistration bug
2020-06-18 12:39:19 +01:00
ben-toogood
5fd36d6cc0 config/cmd: remove package duplicate initialization (#1711) 2020-06-18 10:14:04 +01:00
ben-toogood
3b40fde68b registry/mdns: add domain support (#1708)
* registry: add domain options

* registry/mdns: implement domain options

* registry/mdns: return node domain in metadata when querying using wildcard

* Fix nil pointer exception

* registry/mdns: return error from deregister

* registy/mdns: rename tld => domain
2020-06-17 13:23:41 +01:00
ben-toogood
9d3365c4be auth: rename auth.Namespace to auth.Issuer (#1710) 2020-06-17 12:26:27 +01:00
sunfuze
2efb459c66 Fix config watch (#1670)
* add dirty overrite test case

* need version to figure out if config need update or not

* using nanosecond as version for two goroutine can run in same second

* config should check snapshot version when update

* set checksum of ChangeSet

Co-authored-by: Asim Aslam <asim@aslam.me>
2020-06-16 17:10:52 +01:00
Di Wu
6add74b4f6 Custom private blocks (#1705)
Co-authored-by: Asim Aslam <asim@aslam.me>
2020-06-16 17:05:42 +01:00
Dominic Wong
c67d78f1ef update PR template, not using gitflow anymore 2020-06-16 17:00:15 +01:00
Dominic Wong
a89610ffea Merge pull request #1706 from micro/develop
Develop -> Master. Abandoning gitflow model
2020-06-16 16:57:40 +01:00
Dominic Wong
da9bb11240 Merge branch 'master' into develop 2020-06-16 16:52:24 +01:00
Dmitry Kozlov
a3a1a84172 Split long discord output message into the chunks by 2000 characters (#1704)
Signed-off-by: Dmitry Kozlov <dmitry.f.kozlov@gmail.com>
2020-06-15 22:22:00 +01:00
ben-toogood
1179d7e89a registry/mdns: fix nil host bug (#1703) 2020-06-15 16:13:45 +01:00
Asim Aslam
a5df913926 Update README.md (#1695) 2020-06-12 15:07:19 +01:00
Asim Aslam
9ce706191b Update FUNDING.yml (#1692) 2020-06-12 15:07:19 +01:00
Dominic Wong
0327f30e3c Fix regex detection. Fixes #1663 (#1696) 2020-06-12 10:42:52 +01:00
Dominic Wong
0ce132eb8f Fix race condition when updating process being waited on (#1694) 2020-06-12 10:42:52 +01:00
Janos Dobronszki
00b76e0a64 Initialize selector before we make an auth.Generate call (#1693) 2020-06-12 10:42:52 +01:00
Dominic Wong
aec27be9b4 Fix race when opening DB for first time (#1691) 2020-06-12 10:42:52 +01:00
Dominic Wong
86dfcb819b Ignore "no such process" error (#1686)
* Cleanup how status is updated for service. Ignore "no such process" error as it could be that the pid died

* add nice error log to record process error exit
2020-06-12 10:42:52 +01:00
Janos Dobronszki
d613804b0a Sigterm instead of Sigkill (#1687)
Co-authored-by: Dominic Wong <domwongemail@googlemail.com>
Co-authored-by: Asim Aslam <asim@aslam.me>
2020-06-12 10:42:52 +01:00
92e9d05432 api/handler/rpc: dont log error on normal websocket error code (#1688)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-06-12 10:42:52 +01:00
ben-toogood
8dfd93e915 util/wrapper: Add Static Client wrapper (#1685)
* util/wrapper: Add Static Client wrapper

* util/wrapper/static: pass address to stream too

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* add static client wrapper tests

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* server: fix error message spaces between words

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* server/{rpc,grpc}: replace log.Error with log.Errorf

* server/grpc: fix log typo

* server/rpc: fix log typo

Co-authored-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-06-12 10:42:52 +01:00
Dominic Wong
e5136332e3 Add build and test of micro to pre-release testing (#1684)
* fix up example test build

* build and test micro when cutting a new release
2020-06-12 10:42:52 +01:00
Dominic Wong
f10fd4b479 Build all micro/examples for release-X.X.X branches (#1683)
* Build all the examples on push to any release branch
2020-06-12 10:42:52 +01:00
ben-toogood
74368026a5 Fix incorrect namespace variable name (merge conflict) (#1677) 2020-06-12 10:42:52 +01:00
ben-toogood
fde1aa9d6a Move auth account creation to config/cmd (#1676) 2020-06-12 10:42:52 +01:00
ben-toogood
f45cdba9ba Apply wrappers to gRPC streams (#1675)
* Add wrappers to grpc streams

* Fix typo
2020-06-12 10:42:52 +01:00
Dominic Wong
73c2f25935 Fix regex detection. Fixes #1663 (#1696) 2020-06-10 11:18:03 +01:00
Asim Aslam
b270860b79 Update README.md (#1695) 2020-06-10 10:22:53 +01:00
Dominic Wong
8e81cea96f Fix race condition when updating process being waited on (#1694) 2020-06-10 09:36:41 +01:00
Janos Dobronszki
cdd8f9fd82 Initialize selector before we make an auth.Generate call (#1693) 2020-06-09 12:47:31 +02:00
Asim Aslam
e7ba930236 Update FUNDING.yml (#1692) 2020-06-08 18:12:19 +01:00
Dominic Wong
a346064eaf Fix race when opening DB for first time (#1691) 2020-06-08 16:19:22 +01:00
Dominic Wong
47bdd5c993 Ignore "no such process" error (#1686)
* Cleanup how status is updated for service. Ignore "no such process" error as it could be that the pid died

* add nice error log to record process error exit
2020-06-08 10:47:25 +01:00
Janos Dobronszki
9af12ff9df Sigterm instead of Sigkill (#1687)
Co-authored-by: Dominic Wong <domwongemail@googlemail.com>
Co-authored-by: Asim Aslam <asim@aslam.me>
2020-06-06 14:04:14 +01:00
6c7bcf3883 api/handler/rpc: dont log error on normal websocket error code (#1688)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-06-06 00:03:43 +03:00
ben-toogood
bbc3b7040b util/wrapper: Add Static Client wrapper (#1685)
* util/wrapper: Add Static Client wrapper

* util/wrapper/static: pass address to stream too

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* add static client wrapper tests

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* server: fix error message spaces between words

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* server/{rpc,grpc}: replace log.Error with log.Errorf

* server/grpc: fix log typo

* server/rpc: fix log typo

Co-authored-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-06-05 10:18:35 +01:00
Dominic Wong
582f2e8b94 Add build and test of micro to pre-release testing (#1684)
* fix up example test build

* build and test micro when cutting a new release
2020-06-04 13:46:22 +01:00
Dominic Wong
bd3ef67328 Build all micro/examples for release-X.X.X branches (#1683)
* Build all the examples on push to any release branch
2020-06-04 09:32:17 +01:00
Dominic Wong
1ccd4cd940 Merge branch 'master' into develop 2020-06-03 10:41:39 +01:00
Dominic Wong
aa679f7a73 Create PULL_REQUEST_TEMPLATE.md 2020-06-03 10:32:28 +01:00
ben-toogood
003731ace9 Fix incorrect namespace variable name (merge conflict) (#1677) 2020-06-03 09:48:19 +01:00
Asim Aslam
7b379bf1f1 WIP: Add metadata to store record (#1604)
* Add metadata to store record

* Add metadata to cockroach store

* add metadata to store service implementation

* fix breaking cache test

* Test/fix cockroach metadata usage

* fix store memory metadata bug
2020-06-03 09:45:08 +01:00
ben-toogood
b6f3e8b715 Move auth account creation to config/cmd (#1676) 2020-06-03 09:43:20 +01:00
ben-toogood
8f6ec21b91 Apply wrappers to gRPC streams (#1675)
* Add wrappers to grpc streams

* Fix typo
2020-06-02 17:56:26 +01:00
Dominic Wong
e4e56b0f3f Merge pull request #1671 from sadwxqezc/fix-jwt
Fix jwt revoke
2020-06-02 09:27:14 +01:00
huanghuan.27@bytedance.com
219d29f664 fix jwt revoke 2020-06-02 10:26:33 +08:00
Asim Aslam
8fb138af06 Update README.md 2020-05-31 11:56:55 +01:00
Asim Aslam
a39e6515da Update README.md 2020-05-31 11:35:09 +01:00
Asim Aslam
2c7fd286de Update README.md 2020-05-31 11:34:49 +01:00
Asim Aslam
8aa2712b4d Delete README.zh-cn.md 2020-05-31 11:33:31 +01:00
Asim Aslam
b5c2121cef Update README.md 2020-05-31 11:31:41 +01:00
Asim Aslam
ca9b877646 Update README.md 2020-05-31 11:28:32 +01:00
Asim Aslam
ff49b4fc71 Update README.md 2020-05-31 11:27:54 +01:00
Asim Aslam
222431b57a Update README.md 2020-05-31 11:26:46 +01:00
Asim Aslam
ddb51529a7 Update README.md 2020-05-31 11:26:18 +01:00
Asim Aslam
7c048f331a Update README.md 2020-05-31 11:21:55 +01:00
Asim Aslam
8475183bbb Update README.md 2020-05-31 11:19:26 +01:00
Asim Aslam
10f35db3ed Update README.md 2020-05-31 11:16:20 +01:00
Asim Aslam
b68af8ab63 run go fmt 2020-05-30 11:00:43 +01:00
Asim Aslam
266602a3d6 Update README.md 2020-05-30 10:59:59 +01:00
mlboy
15d5142d9b fix: misspell (#1667) 2020-05-29 17:49:22 +01:00
Máximo Cuadros
0d88650511 go modules cleanup and remove wrong self import to v1 (#1658)
* Runtime local git, simply go-git code
* go modules cleanup and remove wrong self import to v1
* pin mergo v0.3.8 to avoid panics

Signed-off-by: Máximo Cuadros <mcuadros@gmail.com>
Co-authored-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-05-29 14:32:11 +03:00
Dominic Wong
8660370dc9 Merge pull request #1657 from xpunch/master
logger caller not trim in windows
2020-05-29 10:35:03 +01:00
Dominic Wong
73339dde85 Merge branch 'master' into master 2020-05-29 10:27:20 +01:00
Dominic Wong
3f354f3c30 Merge pull request #1661 from micro/bugfix/sock_pool_threads
fix locking of socket pool
2020-05-28 08:31:47 +01:00
potato
c08eb5f892 Merge branch 'master' into master 2020-05-28 10:19:53 +08:00
Dominic Wong
27e41c4ad5 fix locking of socket pool 2020-05-27 20:18:26 +01:00
Dominic Wong
1da8a640da Merge pull request #1660 from micro/bugfix/mdns_nil_host
Check ipv4 or ipv6 address is valid before assigning
2020-05-27 15:53:27 +01:00
Dominic Wong
e7ad031eb8 Check ipv4 or ipv6 address is valid before assigning 2020-05-27 15:47:12 +01:00
ben-toogood
192f548c83 Merge pull request #1659 from micro/config-srv-not-found
Handle config service not found errors
2020-05-27 12:24:33 +01:00
Ben Toogood
d85b4197b4 Return nil changeset and not blank 2020-05-27 12:20:31 +01:00
Ben Toogood
bb5f2e5525 Handle config service not found errors 2020-05-27 12:12:34 +01:00
ben-toogood
f00b696282 Merge pull request #1654 from micro/auth-scopes
Auth Improvements
2020-05-27 10:52:07 +01:00
Ben Toogood
e2d662608c Fix tests 2020-05-27 09:14:16 +01:00
Ben Toogood
9e9773c9c7 Only use namespace for cache key 2020-05-27 09:07:59 +01:00
potato
2f8e2487f7 Merge branch 'master' into master 2020-05-27 09:32:27 +08:00
Ben Toogood
d6c1fbf841 Fix web service auth name 2020-05-26 17:43:45 +01:00
Ben Toogood
c3b404bab0 Fix server calling across namespace 2020-05-26 17:35:06 +01:00
Ben Toogood
cd283654eb Cache Rules 2020-05-26 15:53:28 +01:00
Ben Toogood
5712cc9c62 Merge master 2020-05-26 15:52:21 +01:00
ben-toogood
be5a10a4d4 Merge pull request #1656 from micro/client-cache
Client Cache
2020-05-26 15:38:30 +01:00
Ben Toogood
b53a2c67f1 Merge branch 'master' of https://github.com/micro/go-micro into auth-scopes 2020-05-26 15:37:31 +01:00
johnson
cc79692d68 make caller filepath package/file style
this code is from zap
9a9fa7d4b5/zapcore/entry.go (L101)
2020-05-26 14:33:56 +08:00
potato
796a598b37 Merge pull request #7 from micro/master
go micro v2
2020-05-26 14:18:25 +08:00
Ben Toogood
73b4423682 Merge branch 'master' of https://github.com/micro/go-micro into client-cache 2020-05-24 20:36:22 +01:00
Ben Toogood
198e942889 Remove redundant test 2020-05-24 20:32:22 +01:00
Ben Toogood
95703e4565 Fixes and improved test coverage 2020-05-24 20:26:37 +01:00
Ben Toogood
2729569f66 Add Debug.Cache method 2020-05-24 18:45:57 +01:00
Ben Toogood
67146ecdc2 Client Cache tests 2020-05-24 18:05:23 +01:00
Asim Aslam
bd049a51e6 Update README.md 2020-05-23 16:47:23 +01:00
Asim Aslam
ffd89599a0 Update README.md 2020-05-23 16:46:50 +01:00
Ben Toogood
496293afa1 Use hash/fnv, add tests, fix request bug 2020-05-23 11:34:44 +01:00
Ben Toogood
7d7f4046e8 Client Cache 2020-05-22 16:52:24 +01:00
Ben Toogood
c800070477 Check for error before loading rules 2020-05-22 14:03:12 +01:00
Ben Toogood
877fe5fb0a Update web wildcard to enable /foo/bar/baz/* to verify /foo/bar/baz 2020-05-22 14:02:02 +01:00
Ben Toogood
dad011cab4 Fix noop issuer bug 2020-05-22 12:40:34 +01:00
Ben Toogood
f939200b34 Improve service auth log 2020-05-22 12:24:37 +01:00
Ben Toogood
9c072a372c Add auth scope constants 2020-05-22 11:37:12 +01:00
Ben Toogood
fbb91c6cb7 Auth wrapper tests 2020-05-22 10:44:18 +01:00
Ben Toogood
b2cf501952 Auth Rules tests & bug fixes 2020-05-22 09:31:15 +01:00
Ben Toogood
1fce0f02b6 Verify Namespace 2020-05-21 18:11:35 +01:00
Ben Toogood
12061bd006 Add account issuers 2020-05-21 16:41:55 +01:00
Ben Toogood
856c73b341 Remove roles (replaced with scope) 2020-05-21 14:56:17 +01:00
Ben Toogood
4de19805ba Remove redundant test 2020-05-21 12:33:58 +01:00
Ben Toogood
c09b871a6b Merge branch 'master' of https://github.com/micro/go-micro into auth-scopes 2020-05-21 12:32:52 +01:00
Ben Toogood
e876cb917d auth/service support for micro clients (rules from mutltiple namespaces 2020-05-21 12:25:47 +01:00
Ben Toogood
8f5ef012ff Update Rules.Delete proto 2020-05-21 12:07:22 +01:00
Ben Toogood
287992cef3 Fix service => service namespace bug 2020-05-21 11:35:07 +01:00
Ben Toogood
344ce061ce Verify Options 2020-05-20 16:49:52 +01:00
Ben Toogood
5d14970a55 Fix nil account bug 2020-05-20 16:11:34 +01:00
Janos Dobronszki
0615fe825f Auth invalid token fix (#1650) 2020-05-20 16:18:05 +02:00
Asim Aslam
6a661fd08c check if the db conn is nil before doing anything (#1652) 2020-05-20 14:03:38 +01:00
Ben Toogood
f6d9416a9e Add Rule to Auth interface 2020-05-20 11:59:01 +01:00
Asim Aslam
a29676b86a Registration Retry / Interval (#1651)
* Change the default ttl to 90 seconds

* add retries to registration

* Add retry to web register
2020-05-20 11:49:09 +01:00
Ben Toogood
dc10f88c12 Replace auth account.Namespace with account.Scopes 2020-05-19 18:17:17 +01:00
ben-toogood
e61edf6280 Merge pull request #1645 from micro/runtime-multitenancy
Runtime multi-tenancy
2020-05-19 17:06:11 +01:00
ben-toogood
3410a0949b Merge branch 'master' into runtime-multitenancy 2020-05-19 17:00:51 +01:00
Jake Sanders
9216a47724 fix client race (#1647) 2020-05-19 14:44:46 +01:00
ben-toogood
cf37d64819 Merge branch 'master' into runtime-multitenancy 2020-05-19 13:24:35 +01:00
Patrik Lindahl
f0c0f3d4c4 Fixes for #1560 (#1644)
close #1560

This fixes one of the reported data races and also allows for
having a different name on the micro.Service and web.Service.
This makes it possible to discover the two service variants separately.

Co-authored-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-05-19 14:11:26 +03:00
Ben Toogood
c4e3f8c336 Merge branch 'master' of https://github.com/micro/go-micro into runtime-multitenancy 2020-05-19 11:02:40 +01:00
Ben Toogood
8875719619 Default Runtime multi-tenancy 2020-05-19 11:01:06 +01:00
Ben Toogood
c19b349e96 Update runtime.Event struct 2020-05-19 10:14:07 +01:00
Ben Toogood
14155c7e02 Add runtime ErrNotFound 2020-05-19 09:28:00 +01:00
Maarten Bezemer
3d36398818 Fix client RPC stream close mutex (#1643) 2020-05-18 17:22:33 +01:00
Asim Aslam
56a7897c91 update readme 2020-05-17 12:39:20 +01:00
ben-toogood
5efb386224 Merge pull request #1640 from micro/auth/public-rule
Auth: setup a public rule
2020-05-15 10:28:52 +01:00
Ben Toogood
4d2de923cd Auth: setup a public rule 2020-05-15 10:24:30 +01:00
ben-toogood
f64b1468a5 Merge pull request #1639 from micro/registy-not-found
Registry service: return not found error
2020-05-14 19:43:19 +01:00
ben-toogood
56f281002b Merge branch 'master' into registy-not-found 2020-05-14 19:39:43 +01:00
Ben Toogood
0d7250352f Registry service: return not found error 2020-05-14 19:38:56 +01:00
ben-toogood
ef43f01da4 Merge pull request #1638 from micro/registry-addrs-fix
Fix registry address option unused
2020-05-14 18:07:14 +01:00
ben-toogood
c9e5ae6a2b Merge branch 'master' into registry-addrs-fix 2020-05-14 18:03:46 +01:00
Ben Toogood
8a802d8f7a Fix registry address option unused 2020-05-14 18:00:13 +01:00
ben-toogood
331ab3715c Merge pull request #1636 from micro/auth-util
Refactor auth setup to util/auth
2020-05-14 16:15:47 +01:00
Ben Toogood
6b451a2197 Refactor auth setup to util/auth 2020-05-14 16:10:14 +01:00
ben-toogood
b4c0224746 Merge pull request #1635 from micro/auth-fixes
Auth: Move token generation logic out the client wrappers
2020-05-14 14:00:55 +01:00
Ben Toogood
500d793fc4 Merge branch 'auth-fixes' of https://github.com/micro/go-micro into auth-fixes 2020-05-14 13:57:00 +01:00
Ben Toogood
16af265e8b Seperate JWT refresh / access tokens 2020-05-14 13:56:51 +01:00
ben-toogood
b222cf8e13 Merge branch 'master' into auth-fixes 2020-05-14 13:47:26 +01:00
Ben Toogood
f549e20fa2 tidy go mdo 2020-05-14 13:33:11 +01:00
Ben Toogood
83e9c1fad2 Remove unnecessary change 2020-05-14 13:32:42 +01:00
Ben Toogood
c220686c29 Fix token bug 2020-05-14 13:30:21 +01:00
Ben Toogood
1b18730d54 Custom micro client 2020-05-14 11:25:19 +01:00
Ben Toogood
5764519f5b Refactor auth to load token outside wrappers 2020-05-14 11:06:22 +01:00
ben-toogood
957001f8ad Merge pull request #1634 from micro/disable-clients
Disable Clients
2020-05-13 18:54:34 +01:00
Ben Toogood
0955671e45 Merge branch 'disable-clients' of https://github.com/micro/go-micro into disable-clients 2020-05-13 18:49:47 +01:00
Ben Toogood
57b060bac5 Disable Addresses 2020-05-13 18:49:36 +01:00
ben-toogood
3136e1409e Merge branch 'master' into disable-clients 2020-05-13 18:48:24 +01:00
Ben Toogood
ca791d7e8d Disable Clients 2020-05-13 18:47:53 +01:00
Dominic Wong
05858b746c kill all processes correctly for micro kill command (#1633) 2020-05-13 18:36:45 +01:00
ben-toogood
09d1450d7d Merge pull request #1632 from micro/fix-auth-bug
Auth: Fix recursive bug
2020-05-13 18:18:39 +01:00
Ben Toogood
1ca1fd411a Auth: Fix recursive bug 2020-05-13 18:17:04 +01:00
ben-toogood
a2d4d62f1c Merge pull request #1631 from micro/auth-address
Auth: Set address
2020-05-13 18:02:10 +01:00
Ben Toogood
8ab20f501c Fix merge conflicts 2020-05-13 17:58:03 +01:00
Ben Toogood
366fb228e5 Auth: Set address 2020-05-13 17:54:47 +01:00
Asim Aslam
bba8c254d7 fix auth initialisation (#1630) 2020-05-13 17:35:57 +01:00
ben-toogood
ebd53794af Merge pull request #1629 from micro/auth/rules-fix
Auth: Load rules if not present
2020-05-13 17:27:53 +01:00
Ben Toogood
2299244332 Auth: Load rules if not present 2020-05-13 17:07:46 +01:00
ben-toogood
cf61d98635 Merge pull request #1628 from micro/registry
Misc Muti-Tenancy / Auth Fixes
2020-05-13 16:53:39 +01:00
ben-toogood
15d1967aaf Merge branch 'master' into registry 2020-05-13 16:50:12 +01:00
Ben Toogood
410fec8ee4 Fix auth bug 2020-05-13 16:49:17 +01:00
Ben Toogood
c831b6c03a Fix 2020-05-13 16:35:57 +01:00
Asim Aslam
290595f88e Strip down router code (#1627) 2020-05-13 16:13:36 +01:00
ben-toogood
ba64518ebd Merge pull request #1626 from PieterVoorwinden/master
Check if auth is nil to prevent nilpointer
2020-05-13 15:18:58 +01:00
Pieter Voorwinden
b14d63b4a1 Check if auth is nil to prevent nilpointer 2020-05-13 16:13:23 +02:00
x1nchen
af2db0a0d9 fix: update dependency certmagic (#1625)
module github.com/mholt/certmagic has been renamed github.com/caddyserver/certmagic,
so upgrade on this module will fail.

fix: micro/micro#835

caddyserver/certmagic@v0.10.6 is Maximum upgradeable version with go version 1.13

Higher version use *tls.ClientHelloInfo.SupportsCertificate which only supported in go 1.14
2020-05-13 15:00:13 +01:00
ben-toogood
fb255a7e5a Merge pull request #1622 from micro/registry-multi-tenancy
Registry mutli-tenancy
2020-05-13 13:54:39 +01:00
Ben Toogood
47c1cb433e Store account credentials 2020-05-13 13:48:25 +01:00
Ben Toogood
3fac7d79ab Remove service type role 2020-05-13 13:42:56 +01:00
Ben Toogood
25c937fd0e Naming changes 2020-05-13 13:38:13 +01:00
Ben Toogood
e5c1fbc591 Merge branch 'master' of https://github.com/micro/go-micro into registry-multi-tenancy 2020-05-13 13:35:47 +01:00
Ben Toogood
d781c9ae2d Remove namespace specific logic 2020-05-13 13:35:34 +01:00
Ben Toogood
54951740bf Authenticate on service start 2020-05-13 13:13:11 +01:00
Janos Dobronszki
0fb4734e67 Upload local source code to micro server (#1613) 2020-05-13 12:07:53 +02:00
Ben Toogood
346e034d0a Add mutli-tenancy support to the registry 2020-05-13 10:40:08 +01:00
Asim Aslam
116cc1e9ee Stop parsing proxy address (#1619) 2020-05-12 17:38:22 +01:00
ben-toogood
762a5bc9e8 Merge pull request #1618 from micro/auth-namespace-flag
Auth Namespace Flag
2020-05-12 16:45:42 +01:00
Ben Toogood
d39b723511 Auth Namespace Flag 2020-05-12 16:41:29 +01:00
ben-toogood
5494e935f4 Merge pull request #1617 from micro/k8s/secret-type
K8s: Add Secret Type to yaml template
2020-05-12 14:21:30 +01:00
Ben Toogood
e0863bb7eb K8s: Add Secret Type to yaml template 2020-05-12 14:10:39 +01:00
ben-toogood
89f86167ad Merge pull request #1616 from micro/k8s/secret-template-fix
Fix k8s secret template (yaml)
2020-05-12 11:45:12 +01:00
ben-toogood
dfec1ad6b1 Merge branch 'master' into k8s/secret-template-fix 2020-05-12 11:41:41 +01:00
Ben Toogood
66d3e4a595 Fix k8s secret template (yaml) 2020-05-12 11:40:54 +01:00
Asim Aslam
19a03babc4 Update server.go 2020-05-12 11:32:01 +01:00
ben-toogood
ee24b4f083 Merge pull request #1615 from micro/disable-auth-client
Disable auth service client
2020-05-11 20:38:49 +01:00
Ben Toogood
937ecc8d2f Disable auth service client 2020-05-11 20:38:05 +01:00
ben-toogood
6078adb8bc Merge pull request #1614 from micro/runtime-clients
Runtime Options: Replace client.DefaultClient
2020-05-11 20:05:00 +01:00
ben-toogood
39f18b0b70 Merge branch 'master' into runtime-clients 2020-05-11 18:03:11 +01:00
Ben Toogood
efb64b7dbb Pass client to more of the runtime 2020-05-11 17:57:39 +01:00
Ben Toogood
f892b41299 Add runtime to service.Options() 2020-05-11 17:09:28 +01:00
Janos Dobronszki
1eb63635b5 Adding file upload and download capabilities (#1610) 2020-05-11 14:08:27 +02:00
ben-toogood
688228377b Merge pull request #1612 from micro/auth-options
Auth: pass options in service RPC
2020-05-11 11:53:38 +01:00
Ben Toogood
506006f0fa Auth Options 2020-05-11 11:47:59 +01:00
ben-toogood
22de001a80 Merge pull request #1611 from micro/auth-has-role
Auth account.HasRole
2020-05-11 11:40:20 +01:00
ben-toogood
d90cc8bf2f Merge branch 'master' into auth-has-role 2020-05-11 11:36:06 +01:00
Ben Toogood
5a8f19589b Auth account.HasRole 2020-05-11 11:34:22 +01:00
gggwvg
d61df6363b web: fix advertise address (#1608)
* web: fix advertise address
* web: fix test

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
Co-authored-by: Asim Aslam <asim@aslam.me>
Co-authored-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-05-08 12:31:03 +03:00
ben-toogood
f062013a7b Merge pull request #1607 from micro/k8s-debug
Log k8s Requests
2020-05-07 11:41:43 +01:00
Ben Toogood
fea93a5b7a Log k8s Requests 2020-05-07 11:35:56 +01:00
fztcjjl
30dc29e17f fix ring buffer (#1606) 2020-05-07 10:45:48 +01:00
ben-toogood
5387f73b5d Handle cockroach createDB error (#1603) 2020-05-06 10:58:14 +01:00
90dd1f63c8 api/handler/rpc: fix encoding of inner message (#1601)
* api/handler/rpc: fix encoding of inner message

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-05-04 15:50:53 +03:00
Asim Aslam
38cdb9cc2f Set table name in store 2020-05-01 18:24:35 +01:00
Asim Aslam
b3915b6020 Add store to options (#1600) 2020-05-01 18:05:09 +01:00
Asim Aslam
08a2de1ef5 Account for missing options database/table in cockroach store 2020-05-01 15:31:55 +01:00
Asim Aslam
7a2dea6cc2 Set database/table from init first 2020-05-01 15:22:44 +01:00
Asim Aslam
2a14feed93 force codec on call not on dial (#1599) 2020-05-01 14:59:50 +01:00
Asim Aslam
e8105d22ad cruft 2020-05-01 00:25:17 +01:00
Asim Aslam
c76a5e608d sql fixes 2020-04-30 23:53:54 +01:00
Asim Aslam
359b8bc503 Add opts to service proto (#1517)
* Add opts to service proto

* Support database/table opts
2020-04-30 22:51:25 +01:00
Janos Dobronszki
fccab8ad27 Runtime name should be base folder outside repos (#1598) 2020-04-30 18:20:51 +02:00
Socket
46d09ec2bc unsubscribe can async (#1596)
Co-authored-by: huangshaojie <huangshaojie@corp.netease.com>
Co-authored-by: Asim Aslam <asim@aslam.me>
2020-04-30 10:42:13 +01:00
Asim Aslam
7792dbc34d Update FUNDING.yml 2020-04-29 18:45:55 +01:00
ben-toogood
1d29f126f9 Merge pull request #1595 from micro/auth-client-wrapper
Auth Client Wrapper
2020-04-29 15:43:30 +01:00
Ben Toogood
bcddb98867 Fix Tests 2020-04-29 15:37:02 +01:00
Ben Toogood
f48dec1fb0 Use Server ID in account name 2020-04-29 15:27:18 +01:00
Ben Toogood
ef9f65c78b Improve Comments 2020-04-29 15:15:38 +01:00
Ben Toogood
99f8be5b3d Auth Client Wrapper 2020-04-29 15:11:06 +01:00
ben-toogood
9d2fdb84be Merge pull request #1592 from micro/jwt-auth
JWT auth implementation
2020-04-29 14:10:05 +01:00
ben-toogood
8b004feb9a Merge branch 'master' into jwt-auth 2020-04-29 13:33:47 +01:00
Ben Toogood
70736e24c0 Set RefreshToken 2020-04-29 13:33:22 +01:00
d44adafca5 api/router: avoid unneeded loops and fix path match (#1594)
* api/router: avoid unneeded loops and fix path match

* if match found in google api path syntax, not try pcre loop
* if path is not ending via $ sign, append it to pcre to avoid matching other strings like
  /api/account/register can be matched to /api/account
* api: add tests and validations

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-04-29 15:23:10 +03:00
ben-toogood
e57b20c1f8 Merge branch 'master' into jwt-auth 2020-04-29 13:22:09 +01:00
Ben Toogood
94971aee77 Complete JWT implementation 2020-04-29 13:21:51 +01:00
Ben Toogood
0ed66d0664 Fix Typo 2020-04-29 09:38:39 +01:00
Ben Toogood
7e27c97c6c Remove Comment 2020-04-29 09:22:15 +01:00
Ben Toogood
669364985e JWT auth implementation 2020-04-29 09:21:17 +01:00
Asim Aslam
c7440274dd touch 2020-04-28 19:35:13 +01:00
Asim Aslam
8ccbf53dfc secret cookie unused 2020-04-28 18:12:07 +01:00
Asim Aslam
f908110fb6 swap out context access for account (#1589) 2020-04-28 17:35:18 +01:00
9bb1904a38 broker: add publish context (#1590)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-04-28 19:29:00 +03:00
06220ab8c8 client: add context publish option (#1588)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-04-28 19:03:37 +03:00
Janos Dobronszki
da66561d1e Fixing too large offsets for default runtime logs (#1587) 2020-04-28 13:42:15 +01:00
Dmitry Kozlov
52861310b0 fix HTTP 401 Unauthorized, {"message": "401: Unauthorized", "code": 0} (#1586)
fix file=bot.go:426 level=error service=bot error starting bot HTTP 401 Unauthorized, {"message": "401: Unauthorized", "code": 0}
see https://github.com/bwmarrin/discordgo#usage
2020-04-28 13:06:01 +01:00
414b2ec5f8 web: fix deadlock (#1585)
* web: fix deadlock

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* add web tests

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-04-28 12:23:52 +01:00
Janos Dobronszki
b875868a39 Don't ignore errors from checkout source code (#1584)
Don't check out code for builtin services.
2020-04-28 10:51:39 +02:00
Janos Dobronszki
8148e0a0f8 Micro log fixes (#1570) 2020-04-28 09:49:39 +02:00
ben-toogood
25c82245b1 Merge pull request #1582 from micro/k8s-srv-accounts
Runtime: Add Kubernetes ServiceAccounts & Remove imagePullSecrets
2020-04-27 15:24:16 +01:00
ben-toogood
95a7e21f5f Merge branch 'master' into k8s-srv-accounts 2020-04-27 15:08:24 +01:00
Asim Aslam
83ab47333f rename Codec to Secrets (#1581) 2020-04-27 14:57:57 +01:00
Ben Toogood
8d7d6ef358 Add k8s secrets 2020-04-27 14:37:28 +01:00
Ben Toogood
494e0b5060 Runtime: Add Kubernetes ServiceAccounts & Remove imagePullSecrets 2020-04-27 14:13:51 +01:00
Janos Dobronszki
434997e676 Display only logging file name as opposed to path in logs (#1580) 2020-04-27 09:55:50 +01:00
Janos Dobronszki
ec44b67e9f Fixing log file path in logs (#1578) 2020-04-27 09:36:09 +01:00
e0c9234c0e web: use default logger (#1577)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-04-27 00:03:05 +03:00
980b772801 fix races in web and logger (#1576)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-04-26 17:41:36 +03:00
a22da39e1c logger: add caller info to default implementation (#1575)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-04-26 17:11:53 +03:00
徐旭
7253635cd3 delete invalid copy (#1573)
* prealloc

* delete invalid copy
2020-04-26 12:44:59 +01:00
Asim Aslam
0a030f3d8a strip unused list endpoint 2020-04-24 18:05:38 +01:00
Asim Aslam
edee3b6765 Add proxy env test (#1569) 2020-04-24 11:26:46 +01:00
Asim Aslam
d62ae23a9c Strip label 2020-04-23 20:20:48 +01:00
Asim Aslam
c68226e9b0 only do namespace check if not default 2020-04-23 19:19:13 +01:00
ben-toogood
041d68b1ce Merge pull request #1566 from micro/image-pull-secret-fix
Fix Runtime Namespace List
2020-04-23 18:16:38 +01:00
ben-toogood
85a8f36565 Merge branch 'master' into image-pull-secret-fix 2020-04-23 18:15:04 +01:00
Ben Toogood
f34d58cfbd Remove Debug 2020-04-23 18:14:06 +01:00
Asim Aslam
e0a651bfc3 set namespace on create 2020-04-23 18:10:13 +01:00
Ben Toogood
cd35f503a0 Remove hardcoded labels 2020-04-23 18:08:02 +01:00
Ben Toogood
8b3d223fc0 Remove hardcoded labels: 2020-04-23 18:05:58 +01:00
Ben Toogood
bb25bd94c8 Log k8s requests 2020-04-23 17:56:00 +01:00
ben-toogood
986e3d3c35 Merge pull request #1565 from micro/image-pull-secret-fix
Runtime: Fix ImagePullSecret
2020-04-23 17:53:09 +01:00
Ben Toogood
616db3442a Debugging 2020-04-23 17:44:40 +01:00
Ben Toogood
5fe3c0bfe5 Merge branch 'image-pull-secret-fix' of https://github.com/micro/go-micro into image-pull-secret-fix 2020-04-23 17:37:33 +01:00
Ben Toogood
8849b85a7f Merge branch 'master' of https://github.com/micro/go-micro into image-pull-secret-fix 2020-04-23 17:37:15 +01:00
ben-toogood
893bbafa03 Merge branch 'master' into image-pull-secret-fix 2020-04-23 17:28:06 +01:00
Ben Toogood
4c05623a3c Image pull secret fix 2020-04-23 17:26:59 +01:00
Asim Aslam
ec929b3d2f log error and ensure we pass through namespace 2020-04-23 17:14:30 +01:00
Asim Aslam
2299559397 Check for namespace (#1564) 2020-04-23 16:22:41 +01:00
ben-toogood
6be53536d3 Merge pull request #1562 from micro/git-secrets
Runtime - Image Pull Secrets
2020-04-23 15:45:32 +01:00
ben-toogood
99d4b2b31a Merge branch 'master' into git-secrets 2020-04-23 15:39:37 +01:00
Janos Dobronszki
ff8ad7d4ca Default runtime now checks out code on demand (#1563)
* Default runtime now checks out code on demand

* Go mod tidy
2020-04-23 16:30:43 +02:00
ben-toogood
b692c045b5 Merge branch 'master' into git-secrets 2020-04-23 15:01:47 +01:00
Ben Toogood
b5f53595ca Pass image_pull_secrets in runtime service 2020-04-23 14:22:23 +01:00
Ben Toogood
88176dca53 Remove debugging 2020-04-23 14:13:07 +01:00
Ben Toogood
020476614c Tweak CreateImagePullSecret 2020-04-23 14:06:33 +01:00
Ben Toogood
0f42346976 Additonal Debugging 2020-04-23 14:03:04 +01:00
ben-toogood
692b27578c Runtime Namespace (#1547)
* Add context option to runtime; Add dynamic namespace to kubectl client

* Add namespace runtime arg

* Fixes & Debugging

* Pass options in k8s runtime

* Set namespace on k8s resources

* Additional Logging

* More debugging

* Remove Debugging

* Ensure namespace exists

* Add debugging

* Refactor namespaceExists check

* Fix

* Fix

* Fix

* Fix

* Change the way we check for namespace

* Fix

* Tidying Up

* Fix Test

* Fix merge bugs

* Serialize k8s namespaces

* Add namespace to watch

* Serialize namespace when creating k8s namespace

Co-authored-by: Ben Toogood <ben@micro.mu>
Co-authored-by: Asim Aslam <asim@aslam.me>
2020-04-23 13:53:42 +01:00
Micro
316b81f790 Debugging 2020-04-23 13:11:00 +01:00
Micro
5e3262a62c Passs img pull secrets using name key 2020-04-23 12:52:59 +01:00
Micro
053fa0e457 Fix template syntax 2020-04-23 12:38:00 +01:00
Micro
501a6bf3ea Add imagePullSecrets to PodSpec 2020-04-23 12:27:36 +01:00
Asim Aslam
7345ce9192 change logging for service startup 2020-04-23 11:24:39 +01:00
6fa27373ed bundle qson lib in util (#1561)
* copy qson from https://github.com/joncalhoun/qson
  as author not want to maintain repo
* latest code contains our fix to proper decode strings
  with escaped & symbol
* replace package in api/handler/rpc

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-04-23 11:08:09 +03:00
徐旭
e55c23164a fix prealloc in trace (#1558) 2020-04-22 16:10:59 +03:00
Asim Aslam
e25ab9f4ca Fix typo for proxy 2020-04-22 10:44:34 +01:00
bea092f082 server: set registered only after configuring subscribers (#1557)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-04-21 23:01:59 +03:00
Asim Aslam
d7ecb58f6c Add network proxying (#1556)
* Add network proxying

* go fmt
2020-04-21 15:54:40 +01:00
Jake Sanders
05d2b34e10 Add util/pki for creating and signing certificates (#1555) 2020-04-21 15:03:33 +01:00
ben-toogood
211fd9b9a3 Merge pull request #1554 from micro/oauth-login-hint
Add oauth login hint param
2020-04-21 13:40:47 +01:00
Ben Toogood
19f0836e70 Add oauth login hint param 2020-04-21 13:37:26 +01:00
Janos Dobronszki
075d7d4fef Renaming ShutdownSignals -> Shutdown (#1553) 2020-04-21 14:14:20 +02:00
Janos Dobronszki
e5c215556e Add SIGKILL to shutdown signals (#1552)
* Add SIGKILL to shutdown signals

* go mod tidy

* Add missing file
2020-04-21 14:00:12 +02:00
Janos Dobronszki
7c31edd5f8 Enabling default runtime to run multiple versions (#1545)
* Enabling default runtime to run multiple versions

* Trigger build

* Fix

* Sprintf
2020-04-20 15:54:29 +02:00
Asim Aslam
c4acf3c2cb Static serving disabled 2020-04-19 20:30:38 +01:00
Asim Aslam
53db26a614 Use go.micro.mu 2020-04-19 17:03:25 +01:00
Asim Aslam
dde8f18b52 Update readme 2020-04-19 00:46:33 +01:00
Asim Aslam
6071b74fb5 Update readme 2020-04-19 00:45:29 +01:00
Asim Aslam
ab041012b2 Update readme 2020-04-19 00:44:52 +01:00
Asim Aslam
226d6ad22b log whats happening in http handler 2020-04-19 00:41:03 +01:00
Asim Aslam
a08ff90976 fix this bs logging issue 2020-04-18 23:36:00 +01:00
Asim Aslam
ae8404d760 Log listening port 2020-04-18 23:32:20 +01:00
f00fd7a49e api/router: support pcre and google.api pattern matching (#1549)
* api/router: support pcre and google.api pattern matching

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-04-19 00:31:34 +03:00
Asim Aslam
ecbc42755c set network nodes in http resolver 2020-04-18 21:00:00 +01:00
Asim Aslam
16db76bee2 remove list endpoint from runtime and stop checking type in update 2020-04-17 17:54:34 +01:00
Asim Aslam
dca5305e8a replaced build with updated timestamp in runtime 2020-04-17 16:29:05 +01:00
Asim Aslam
c0b0f63757 Update docker workflow to push releases 2020-04-17 10:50:44 +01:00
Janos Dobronszki
ac5822f1ee Fix local runtime updates (#1543) 2020-04-16 17:50:24 +02:00
ben-toogood
ae56becbbd Merge pull request #1542 from micro/stream-auth
Set authorization header on grpc stream
2020-04-16 15:06:19 +01:00
ben-toogood
5bb18e685e Merge branch 'master' into stream-auth 2020-04-16 15:03:12 +01:00
Ben Toogood
2dfaab439c Set authorization header on grpc stream 2020-04-16 15:01:16 +01:00
62cedf64da api/router/registry: extract path based parameters from url to req (#1530)
* api/router/registry: extract path based parameters from url to req
* api/handler/rpc: fix empty body request parsing
* bundle grpc-gateway util funcs

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-04-15 17:50:51 +03:00
ben-toogood
9961ebb46e Merge pull request #1538 from micro/rule-priority
Add priority to auth.CreateRequest and auth.DeleteRequest
2020-04-15 11:54:01 +01:00
Ben Toogood
fe31a71557 Fix formatting 2020-04-15 11:50:52 +01:00
Ben Toogood
c9a6b07c52 Add priority to auth.CreateRequest and auth.DeleteRequest 2020-04-15 11:49:24 +01:00
ben-toogood
f1e6eff303 Merge pull request #1537 from micro/rule-priority
Add Priority to auth rules
2020-04-15 11:42:53 +01:00
Ben Toogood
2de03e5fd7 Tidy go mod 2020-04-15 11:39:53 +01:00
Ben Toogood
234c192faf Update protoc-gen-micro 2020-04-15 11:39:12 +01:00
Ben Toogood
ea29920afb Add Priority to auth rules 2020-04-15 11:31:19 +01:00
4d177a782e vendor proto files from google (#1536)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-04-15 13:22:32 +03:00
b700d425a4 api/handler/rpc: improvements and fixes (#1535)
* api/handler/rpc: fix empty body case
* api/handler/rpc: copy all request headers to metadata

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-04-15 01:37:15 +03:00
Asim Aslam
9a5b8ff50d use api 2020-04-14 22:14:55 +01:00
Asim Aslam
c787fd0483 fix missing pointer 2020-04-14 17:13:38 +01:00
Asim Aslam
1134ea5ff3 make proto.Message compatible with raw json 2020-04-14 16:59:24 +01:00
ben-toogood
fd16cd298f Merge pull request #1532 from micro/registry-namespace
Registry Namespace
2020-04-14 16:14:18 +01:00
ben-toogood
67e7aa223a Merge branch 'master' into registry-namespace 2020-04-14 16:03:29 +01:00
Asim Aslam
9d0381306d add a proto message without serialisation 2020-04-14 15:54:25 +01:00
ben-toogood
f8837bfcbd Merge branch 'master' into registry-namespace 2020-04-14 15:37:44 +01:00
268651df18 regenerate all proto based files (#1531)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-04-14 16:25:09 +03:00
Ben Toogood
e17825474f Add context options to the runtime 2020-04-14 12:32:59 +01:00
Ben Toogood
0c75a0306b Merge master into registry-namespace 2020-04-14 09:15:13 +01:00
Ben Toogood
d61d30ef66 Inject Namespace into Context 2020-04-14 09:14:07 +01:00
Asim Aslam
71d4253927 Merge branch 'master' of ssh://github.com/micro/go-micro 2020-04-13 23:05:47 +01:00
Asim Aslam
e515005083 Remove only allowing certain methods 2020-04-13 23:05:39 +01:00
Asim Aslam
4bdc18d64a Update README.md 2020-04-13 22:15:21 +01:00
Asim Aslam
f840a5003e Remove runtime List 2020-04-12 23:46:06 +01:00
Asim Aslam
5ef1698632 remove readme 2020-04-12 23:43:55 +01:00
Asim Aslam
1bb6967a38 reorder 2020-04-12 23:41:21 +01:00
Asim Aslam
a056bdce7c fix metadata parsing 2020-04-12 14:40:37 +01:00
Asim Aslam
b08c636b44 fixup handler tests 2020-04-12 14:29:38 +01:00
Asim Aslam
d03a02f2e4 fix import 2020-04-12 11:25:12 +01:00
Asim Aslam
08ca61c121 add metadata set 2020-04-12 11:17:23 +01:00
Asim Aslam
962588b649 Strip MetadataKey global var 2020-04-12 11:16:08 +01:00
Asim Aslam
cf67d460b7 strip down mdns watcher 2020-04-12 11:01:09 +01:00
Asim Aslam
4e539361fa strip file 2020-04-12 10:58:12 +01:00
3ce2ab88f5 broker/nats: remove embed nats server reference (#1527)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-04-11 22:37:29 +03:00
0a2363b49b api minor improvements (#1526)
* api/handler/rpc: unblock all http methods and set Host meta
* api/router/static: add debug log

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-04-11 22:21:55 +03:00
Asim Aslam
ec80ceb8c2 Update readme 2020-04-11 18:23:37 +01:00
Asim Aslam
ea2bb0275c Strip external use of mdns 2020-04-11 13:02:53 +01:00
Asim Aslam
51d4f737b8 fixup store cache# 2020-04-11 12:10:19 +01:00
Asim Aslam
3f81f685df Move sync 2020-04-11 12:00:34 +01:00
Asim Aslam
bb1ccf09e8 prefix store dir 2020-04-11 11:23:41 +01:00
Asim Aslam
c878237567 fix log file creation 2020-04-11 11:22:02 +01:00
Asim Aslam
ac8b6f944e Prefix logs dir micro/logs for runtime 2020-04-11 11:15:01 +01:00
Asim Aslam
0f2006ac50 fix compilation issues 2020-04-11 11:02:06 +01:00
Asim Aslam
c697eed1be Update comments 2020-04-11 10:48:32 +01:00
Asim Aslam
b887d91f94 remove readme 2020-04-11 10:38:13 +01:00
Asim Aslam
39470c1b11 Completely replace sync implementation 2020-04-11 10:37:54 +01:00
Asim Aslam
6d553cb6fe add whitespace 2020-04-11 09:34:04 +01:00
Asim Aslam
c612d86480 Move sync store 2020-04-11 09:33:10 +01:00
Asim Aslam
3f3d2f5027 fixup broker http address 2020-04-11 01:51:26 +01:00
bc71640fd9 broker: swap default broker from eats to http (#1524)
* broker: swap default broker from eats to http

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-04-11 03:46:54 +03:00
Asim Aslam
b979db6d9d remove sync event 2020-04-10 23:29:15 +01:00
Asim Aslam
57b758db7e push 2020-04-10 22:09:06 +01:00
Asim Aslam
b5f546b137 go mod tidy 2020-04-10 19:55:45 +01:00
Asim Aslam
d4b2c948dd Remove cloudflare store 2020-04-10 19:50:57 +01:00
Asim Aslam
b9a5e9d610 fixup sync map 2020-04-10 17:47:13 +01:00
Asim Aslam
57853b2849 remove etcd store 2020-04-10 17:43:02 +01:00
Asim Aslam
e5268dd0a6 move reg util to own package (#1523)
* move reg util to own package

* fix test

* fix broken static router
2020-04-10 17:41:10 +01:00
Asim Aslam
4fd12430d0 cleanup mdns files 2020-04-10 17:19:26 +01:00
Asim Aslam
d134b469be rename file 2020-04-10 17:17:24 +01:00
Asim Aslam
9a685b2df5 delete k8s registry (#1522) 2020-04-10 17:15:20 +01:00
Jake Sanders
6a666c9c7d Add json tags to store.Record (#1518) 2020-04-09 19:38:43 +01:00
Asim Aslam
53549b6b30 Add options for Database/Table (#1516)
* Add options for Database/Table

* fix opts
2020-04-09 17:56:13 +01:00
Jake Sanders
0a27a08184 Add Databases and Tables endpoints to store RPC proto (#1515)
* Add Databases and Tables to store RPC

* add Database to TablesRequest
2020-04-09 16:37:32 +01:00
Janos Dobronszki
77f0abb0ba Enabling micro run for subfolders (#1510)
* Enabling micro run for subfolders

* Use source instead of os.Args[2]

* Works now

* PR comments

* WorkDir -> Dir
2020-04-09 15:44:39 +01:00
Asim Aslam
29cccd0b4a minor tweak add log line to proxy and basic auth provider by default (#1513) 2020-04-09 14:10:17 +01:00
ben-toogood
bf65dc71c7 Merge pull request #1505 from micro/resover-refactor
Extract Micro Resolver (Namespace)
2020-04-09 13:14:49 +01:00
Asim Aslam
5bc8ee39f7 Merge branch 'master' into resover-refactor 2020-04-09 13:07:05 +01:00
8c1b477279 store/cockroach: fixup test (#1512)
* store/cockroach: fixup test

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-04-09 14:58:50 +03:00
Ben Toogood
f9cfbe96c0 Merge master into resover-refactor 2020-04-09 12:42:34 +01:00
Jake Sanders
2e379ca7d0 Don't break the build! 2020-04-09 12:18:02 +01:00
Jake Sanders
2659215d5e cockroachDB doesn't support this syntax (#1509) 2020-04-09 12:11:24 +01:00
1063b954de dont display t.Log/t.Logf as errors in github actions (#1508)
* fix tests and github action annotations

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-04-09 14:05:46 +03:00
Ben Toogood
4ff959ef50 Dynamic Namespace 2020-04-09 11:03:33 +01:00
Janos Dobronszki
bc1c8223e6 Remove ugly unneeded log in runtime local (#1507) 2020-04-09 11:50:12 +02:00
Ben Toogood
27eb7db1c2 Add default resolver to api router 2020-04-09 10:34:21 +01:00
Ben Toogood
3ede494945 Change import name 2020-04-09 10:32:08 +01:00
Ben Toogood
f102aba4c1 Fix HTTP tests 2020-04-09 10:28:38 +01:00
Asim Aslam
f2dd091ec0 strip log 2020-04-09 10:28:16 +01:00
Asim Aslam
c1ad6d6c7c set service name in web 2020-04-09 09:41:50 +01:00
Jake Sanders
1e7cd8c484 Make the constraint explicit rather than inferred (#1506) 2020-04-08 23:52:35 +01:00
Asim Aslam
bf8ebf8ad2 add namespace 2020-04-08 23:27:32 +01:00
Asim Aslam
1768958af7 fix typo 2020-04-08 22:50:56 +01:00
Asim Aslam
bf41d8d28e fix store table env var 2020-04-08 19:44:49 +01:00
Asim Aslam
45700eaabe set database/table in header 2020-04-08 19:25:57 +01:00
Asim Aslam
48dd30c4c2 fix http test 2020-04-08 19:20:43 +01:00
Ben Toogood
8ff86ae08b Extract micro resolver 2020-04-08 16:21:53 +01:00
Asim Aslam
b2079669f7 Strip namespace from router 2020-04-08 15:39:01 +01:00
Asim Aslam
2c1d1afd71 Strip namespace from registry router 2020-04-08 15:38:02 +01:00
Asim Aslam
9a73828782 Remove unused handlers 2020-04-08 15:34:11 +01:00
ben-toogood
c5d085cff8 Merge pull request #1496 from micro/namespace
Configurable Namespace & Public Suffix Domain Resolution
2020-04-08 13:48:50 +01:00
ben-toogood
9f4286fc4e Merge branch 'master' into namespace 2020-04-08 13:44:46 +01:00
Jake Sanders
77f5cc5023 Fix nil dereference in cloudflare store (#1504) 2020-04-08 13:00:30 +01:00
8400aba81c broker/memory: small memory improvements (#1501)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-04-08 14:56:54 +03:00
Jake Sanders
cc027d900e Close statements, add default table if the store was not initialised through service.Init() (#1502) 2020-04-08 12:08:08 +01:00
Edward
bc0dc2e509 fix :no syscall.Kill on windows #1474 (#1474) 2020-04-08 10:50:44 +01:00
1fbc056dd4 minimize allocations (#1472)
* server: minimize allocations on re-register

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* server: stop old instance before Init()

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* client/grpc: fix allocations in protobuf marshal

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* codec/json: fix allocations in protobuf marshal

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* remove stop from init

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* codec/grpc: expose MaxMessageSize

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* codec: use buffer pool

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* metadata: minimize reallocations

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* util/wrapper: use metadata helper

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* registry/cache: move logs to debug level

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* server: move logs to debug level

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* server: cache service only when Advertise is ip addr

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* server: use metadata.Copy

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-04-08 10:50:19 +01:00
Asim Aslam
98fc3dfbad use single data bucket 2020-04-08 09:57:51 +01:00
Asim Aslam
4b0e27413e add Store Close method (#1500)
* add Store Close method

* Update sync store build failure
2020-04-08 09:51:10 +01:00
ben-toogood
6b524e2c55 Merge branch 'master' into namespace 2020-04-08 09:12:28 +01:00
Asim Aslam
4cac7dcc48 fix file tests 2020-04-07 19:45:27 +01:00
Ben Toogood
e907d24e3b API Wrappers 2020-04-07 19:29:26 +01:00
Asim Aslam
39c352f210 Remove the test that takes 30 seconds sleeping 2020-04-07 18:22:40 +01:00
Ben Toogood
67cd59d7bc Rename namespace from Resolver.Endpoint 2020-04-07 16:27:59 +01:00
Ben Toogood
3735b0e529 Remove global namespace option 2020-04-07 16:27:01 +01:00
Ben Toogood
4362a885eb Refactor Namespace Resolver 2020-04-07 16:24:51 +01:00
Janos Dobronszki
038b936ce9 Setting up file store in constructor and not in init which is o… (#1499) 2020-04-07 16:43:43 +02:00
6aaad7d63f api/router/static: allow to specify body dst (#1486)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-04-07 15:38:27 +01:00
Janos Dobronszki
aaee01b1a7 Use file store by default (as opposed to memory store) (#1498)
* Use file store by default (as opposed to memory store)

* Default table for file store
2020-04-07 15:19:45 +02:00
Jake Sanders
71538adfdc Explicitly set the table name during service init (#1497) 2020-04-07 13:00:05 +01:00
Janos Dobronszki
2ea5b33955 Disk backed local store (#1491) 2020-04-07 13:53:22 +02:00
Ben Toogood
3df87510a1 Add namespace 2020-04-07 12:46:44 +01:00
Ben Toogood
9d598836c3 Fix Tests 2020-04-07 11:37:04 +01:00
Ben Toogood
05ac3ff274 Tweak 2020-04-07 11:24:13 +01:00
Ben Toogood
76f6f80318 Default to Hostname 2020-04-07 11:23:21 +01:00
Ben Toogood
cb96949551 Merge branch 'master' of https://github.com/micro/go-micro into namespace 2020-04-07 10:58:54 +01:00
ben-toogood
87cc4f273b Merge pull request #1495 from micro/log-level
Change cross namespace request err level
2020-04-07 10:58:22 +01:00
Ben Toogood
f0980e9b30 Change cross namespace request err level 2020-04-07 10:54:27 +01:00
Ben Toogood
977934f8fd ServiceNamespace => ServicePrefix in api server 2020-04-07 10:39:27 +01:00
Ben Toogood
9e116731b1 ServiceNamespace => ServicePrefix in api server 2020-04-07 10:38:27 +01:00
Ben Toogood
316424f0f7 Fix comments typo 2020-04-07 10:35:57 +01:00
Ben Toogood
bd23dc1f18 Improve micro.mu check 2020-04-07 10:34:26 +01:00
Ben Toogood
501fc5c059 Refactor to use publicsuffix 2020-04-07 10:28:39 +01:00
Ben Toogood
11e1e9120a Remove debugging 2020-04-07 10:10:37 +01:00
Ben Toogood
a81d86ed08 Merge Asim's Fixes 2020-04-07 10:08:06 +01:00
Ben Toogood
7206d5f964 Add Namespace to CombinedAuthHandler 2020-04-07 09:40:40 +01:00
Asim Aslam
b5f5027549 Move store scope to util 2020-04-07 02:23:16 +01:00
Asim Aslam
e8a86585da contains missing host port 2020-04-07 00:54:27 +01:00
Asim Aslam
5374896ed0 clone request 2020-04-07 00:29:35 +01:00
Asim Aslam
b6348ba59a Fix cruft 2020-04-07 00:25:11 +01:00
Asim Aslam
ca11c4a672 Few nitpicks 2020-04-07 00:19:49 +01:00
Lars Lehtonen
900b2d24f9 config/secrets/box: fix dropped test error (#1494) 2020-04-06 23:09:42 +01:00
Jake Sanders
3324d140c0 Rename store Namespace / Prefix options to Database and Table (#1492)
* Rename Namespace to DB, Rename Prefix to table, Remove Suffix Option

* Rename options

* Rename options

* Add store_table option

* Table per service, not Database per service
2020-04-06 16:45:55 +01:00
ben-toogood
3a378eb7d6 Merge pull request #1493 from micro/auth-encode-endpoint
Encode Endpoint in API auth wrapper
2020-04-06 16:21:14 +01:00
Ben Toogood
574bf5ac69 Set value in context, not metadata 2020-04-06 16:10:08 +01:00
Ben Toogood
774c0d30a7 Encode Endpoint in API auth wrapper 2020-04-06 16:01:42 +01:00
ben-toogood
0f570d98e1 Merge pull request #1475 from micro/auth-resolver
Auth integrate resolver to support micro web & api
2020-04-06 14:57:41 +01:00
ben-toogood
7f07e1a642 Merge branch 'master' into auth-resolver 2020-04-06 14:43:22 +01:00
ben-toogood
9b546a7242 Change auth namespace log level (#1490)
Co-authored-by: Ben Toogood <ben@micro.mu>
2020-04-06 13:51:28 +01:00
Asim Aslam
c4442a7533 Don't set the registry in new options for web services (#1489) 2020-04-06 13:40:40 +01:00
ben-toogood
bea7c3f7e7 Merge pull request #1488 from micro/disable-warn-log
Change namespace error log level
2020-04-06 12:55:47 +01:00
ben-toogood
cca9773269 Merge branch 'master' into disable-warn-log 2020-04-06 12:51:47 +01:00
Ben Toogood
600b20fb81 Change namespace error log level 2020-04-06 12:50:04 +01:00
Edward
31a1ea6fae fix: use registry from opts not use default directly:(#1436) (#1468)
web: use passed user registry, or default
2020-04-05 13:15:38 +03:00
bc7579f1d8 api/handler/rpc: fix panic on invalid error conversation (#1483)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-04-04 00:55:15 +03:00
38aed6f0f6 api/handler/rpc: not log error on client disconnect (#1482)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-04-04 00:37:18 +03:00
ben-toogood
7f8b35e295 Merge pull request #1480 from micro/host-fix
Add Debugging
2020-04-03 15:07:22 +01:00
ben-toogood
b09dd9a689 Merge branch 'master' into host-fix 2020-04-03 15:03:49 +01:00
Ben Toogood
a82ce4d1ae Add Debug 2020-04-03 15:03:18 +01:00
ben-toogood
34234fc486 Merge pull request #1479 from micro/host-fix
Auth host fix
2020-04-03 14:43:35 +01:00
Ben Toogood
4a850ff8a0 Auth host fix 2020-04-03 14:40:24 +01:00
ben-toogood
350dd41732 Merge branch 'master' into auth-resolver 2020-04-03 14:19:03 +01:00
ben-toogood
d8cca31738 Merge pull request #1478 from micro/auth-hosts-fix
Fix auth hosts bug
2020-04-03 14:13:51 +01:00
Ben Toogood
b864b3e350 Fix auth hosts bug 2020-04-03 14:09:25 +01:00
ben-toogood
41b746e435 Merge pull request #1477 from micro/fix
Hotfix
2020-04-03 13:37:50 +01:00
Ben Toogood
906263291b Hotfix 2020-04-03 13:37:02 +01:00
ben-toogood
46f0bda31e Merge pull request #1476 from micro/namespace-fix
Namespace Fix
2020-04-03 13:30:30 +01:00
Ben Toogood
d0e47206cc Fix 2020-04-03 13:29:48 +01:00
ben-toogood
ed6fe67880 Merge pull request #1471 from micro/namespace
Detect & Propagate Namespace
2020-04-03 13:07:26 +01:00
Ben Toogood
1374a9e528 Fix namespace bug in auth wrapper 2020-04-03 13:03:27 +01:00
Ben Toogood
a9c0e043d2 Fix nil grpc server auth bug 2020-04-03 12:50:50 +01:00
Ben Toogood
49a568e9c0 Set default server auth 2020-04-03 12:33:19 +01:00
Ben Toogood
dea2d7ab9f Fix go-micro auth wrapper init 2020-04-03 12:27:01 +01:00
Ben Toogood
ebb1a42d48 Merge branch 'namespace' of https://github.com/micro/go-micro into namespace 2020-04-03 12:14:26 +01:00
Ben Toogood
1096c8fb39 Fix failing test 2020-04-03 10:16:19 +01:00
Ben Toogood
91b9c3f92e Add defaults 2020-04-03 10:08:39 +01:00
Ben Toogood
183c8bfb81 Apply fix for apis 2020-04-03 09:45:39 +01:00
Ben Toogood
49a1130281 Merge branch 'auth-resolver' of https://github.com/micro/go-micro into auth-resolver 2020-04-03 09:34:57 +01:00
Ben Toogood
760233b858 Reverse Change 2020-04-03 09:34:52 +01:00
ben-toogood
ede076e899 Merge branch 'master' into auth-resolver 2020-04-03 09:33:13 +01:00
Ben Toogood
fdcb013f24 Fix web registry compatability bugs 2020-04-03 09:18:30 +01:00
Ben Toogood
ce23ab36cb Improve Err Handling 2020-04-02 18:41:06 +01:00
ben-toogood
61f0619e97 Merge branch 'master' into namespace 2020-04-02 18:05:21 +01:00
Ben Toogood
cfde3ec3d9 Remove resolver logic 2020-04-02 18:03:57 +01:00
Ben Toogood
4a4c666528 Remove resolver logic 2020-04-02 18:03:21 +01:00
Ben Toogood
8b35c264eb Pass resolver to api auth handler 2020-04-02 17:44:48 +01:00
Ben Toogood
4999f6dfd4 Namespace requests coming via api & web 2020-04-02 17:01:06 +01:00
Asim Aslam
31c4452fc7 delete monitor (#1470) 2020-04-02 14:05:17 +01:00
Janos Dobronszki
2cafa289b6 Stop LogStream if there is an error in k8s pod log streaming (#1469)
* Stop LogStream if there is an error in k8s pod log streaming

* Locking stream Stops

* PR comment
2020-04-02 12:16:35 +01:00
0241197c6a api/handler/rpc: binary streaming support (#1466)
* api/handler/rpc: binary streaming support

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* fixup

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* fix

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* fix sec webscoekt protol

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-04-02 10:13:04 +01:00
Asim Aslam
0a15ae9b9d Move String method (#1467) 2020-04-01 23:27:15 +01:00
Janos Dobronszki
d2b6d35220 log.Errorf when pod streaming fails (#1463)
* log.Errorf when pod streaming fails

* Error method added for loggers

Co-authored-by: Asim Aslam <asim@aslam.me>
2020-04-01 23:03:26 +01:00
Asim Aslam
e1bc0f6288 replace strings for store prefix (#1465)
Co-authored-by: ben-toogood <bentoogood@gmail.com>
2020-04-01 20:19:21 +01:00
ben-toogood
cd3d704aa5 Merge pull request #1459 from micro/auth-interface-update
Auth Interface Iteration
2020-04-01 17:56:38 +01:00
Ben Toogood
9de69529ce Fix token tests 2020-04-01 17:29:17 +01:00
ben-toogood
623f0c0c90 Merge branch 'master' into auth-interface-update 2020-04-01 17:24:01 +01:00
Ben Toogood
c766679687 Fix typo 2020-04-01 17:22:01 +01:00
Ben Toogood
df8c0bb5e1 Auth Generate, make secret optional 2020-04-01 17:20:02 +01:00
Ben Toogood
d577c32563 Add back auth.PrivateKey 2020-04-01 17:17:40 +01:00
Ben Toogood
365dfe9df5 Code => State 2020-04-01 17:11:46 +01:00
Ben Toogood
ae15793fc3 Support oauth codes 2020-04-01 15:36:22 +01:00
Janos Dobronszki
15fcd5ecef Remove Go micro 1.18 dependency (#1462) 2020-04-01 16:14:08 +02:00
Ben Toogood
1750fd8d10 Merge branch 'auth-interface-update' of https://github.com/micro/go-micro into auth-interface-update 2020-04-01 14:42:37 +01:00
Ben Toogood
525ab094c8 Remove LoginOptions 2020-04-01 14:42:11 +01:00
Janos Dobronszki
bb51b8203e Runtime logs (#1447)
* Runtime logs

* Slightly broken

* Pushing for diff

* Log trailing works locally

* LogsOptions

* Comments and streamcount support for local logs

* Adding kubernetes logs

* Fixing k8s logs

* K8s fixes

* StreamCount is now nuked

* PR comments

* PR comments again

* Fix typo
2020-04-01 15:40:15 +02:00
ben-toogood
75a75c56ad Merge branch 'master' into auth-interface-update 2020-04-01 14:37:06 +01:00
Ben Toogood
26cb6bf5b9 Remove Legacy JWT fields 2020-04-01 14:27:56 +01:00
Ben Toogood
9cbbd71855 Remove default login 2020-04-01 14:26:24 +01:00
Ben Toogood
f7655b71ea Merge branch 'auth-interface-update' of https://github.com/micro/go-micro into auth-interface-update 2020-04-01 14:25:07 +01:00
Ben Toogood
8e4d9e1702 Further Refactoring 2020-04-01 14:25:00 +01:00
Asim Aslam
20c95d94cd api completeness (#1460) 2020-04-01 12:07:50 +01:00
ben-toogood
0a7d8afe67 Merge branch 'master' into auth-interface-update 2020-04-01 09:42:45 +01:00
7b7a859a03 api: use http request Clone (#1458)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-04-01 01:50:37 +03:00
8a8742f867 api/handler/rpc: dont change types of url fields (#1457)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-04-01 01:26:58 +03:00
Asim Aslam
68b0238a5d add stream timeout option which defaults to 0 (#1456)
* add stream timeout option which defaults to 0

* fix option
2020-03-31 23:22:11 +01:00
1490aff38e api/handler/rpc: correctly parse nested url vars (#1455)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-04-01 00:23:17 +03:00
3a22efbd7d metadata: change method name (#1454)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-31 23:39:18 +03:00
5e65a46be3 metadata: allow to remove key from metadata (#1453)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-31 22:55:33 +03:00
18061723bb fix api metadata extract from context (#1452)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-31 22:36:51 +03:00
d6bef84de0 api/handler/rpc: fix metadata cleanup (#1451)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-31 21:59:35 +03:00
Ben Toogood
82bc3cbf8d Update interface to add provider and make secret optional 2020-03-31 19:01:43 +01:00
Ben Toogood
cffb0a1eae Remove ContextWithToken 2020-03-31 18:34:31 +01:00
Ben Toogood
134bc1c68a Implement new interface 2020-03-31 18:17:01 +01:00
Asim Aslam
6c6c5359b1 Add options to config (#1450) 2020-03-31 17:13:21 +01:00
Ben Toogood
8dbb5153f4 Tweak Auth Interface 2020-03-31 17:01:51 +01:00
ben-toogood
2674790694 Service => Service Auth (#1448)
* Service => Service Auth

* WithServicePrivileges => ServicePrivileges

* Fixes for CLI login

* ServicePrivileges => ServiceToken

* Fallback to service token

Co-authored-by: Ben Toogood <ben@micro.mu>
2020-03-31 16:18:04 +01:00
ben-toogood
9fb1d476a2 Merge branch 'master' into auth-srv-srv 2020-03-31 16:15:17 +01:00
Ben Toogood
36386354d7 Fallback to service token 2020-03-31 13:51:32 +01:00
Ben Toogood
bd70820b6b ServicePrivileges => ServiceToken 2020-03-31 13:48:28 +01:00
Ben Toogood
956029ae3d Fixes for CLI login 2020-03-31 13:30:14 +01:00
Ben Toogood
e0c7f48d20 WithServicePrivileges => ServicePrivileges 2020-03-31 12:57:38 +01:00
Ben Toogood
d659e435c6 Service => Service Auth 2020-03-31 12:44:34 +01:00
Jake Sanders
3d274ab6a2 Add namespace support to Kubernetes client (#1446)
* Add namespace support to Kubernetes client

* Fix LastUpdateTime Condition
2020-03-31 12:03:32 +01:00
Asim Aslam
1222d076f2 There can be only one! (#1445)
* There can be only one

* fix proto?
2020-03-31 10:18:50 +01:00
ben-toogood
76ade7efd9 Auth - Swap Refresh to Token and change secrets to be strings, not tokens (#1444)
* Refresh => Token

* Secret is no longer a token

Co-authored-by: Ben Toogood <ben@micro.mu>
2020-03-31 10:06:13 +01:00
c706ebe3fb auth proto: provide help to protoc-gen-go (#1442)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-31 00:35:11 +03:00
9e6db79860 regenerate all proto (#1440)
* regenerate all proto

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* regenerate from proto

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* regenerate from proto

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-30 21:58:32 +01:00
756b346672 auth/service: move all proto files to single dir (#1439)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-30 18:23:00 +03:00
ben-toogood
4db2f5e79d Add Namespace to Auth (#1438)
Co-authored-by: Ben Toogood <ben@micro.mu>
2020-03-30 09:51:37 +01:00
3d7d5ce6b4 api: add static router and improve path parser in rpc handler (#1437)
* api: add static router and improve path parser in rpc handler

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* expose metadata context key to be able to get unmodified map keys

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* server/grpc: fix jsonpb codec for protobuf msg

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* api/handler/rpc: write 204 status code when rsp is nil

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* api/handler/rpc: add check for nil response for non javascript

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-30 09:04:59 +01:00
Socket
8282e781e4 grpc pool should check state (#1435)
Co-authored-by: huangshaojie <huangshaojie@corp.netease.com>
2020-03-28 08:48:25 +00:00
e4acc63d5f add mdns registry debug (#1434)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-27 22:33:49 +03:00
Asim Aslam
45ee5e9ad1 Move error for api validation to trace level (#1432)
* remove error on endpoint validation

* trace level
2020-03-27 14:01:47 +00:00
Asim Aslam
b60fde0e64 Pass through source and metadata in Update and Delete calls to runtime (#1431) 2020-03-27 11:37:12 +00:00
Lars Lehtonen
011a783a9e store/cockroach: fix dropped test errors (#1419)
Co-authored-by: Asim Aslam <asim@aslam.me>
2020-03-27 10:15:37 +00:00
ben-toogood
6723d17b22 Default auth, return account secret on Inspect (#1430)
Co-authored-by: Ben Toogood <ben@micro.mu>
2020-03-27 09:54:29 +00:00
ben-toogood
47c7181d41 Default Auth: Add blank secret to account to prevent nil errors (#1429)
* Remove debug auth logs

* Default auth, return account secret on Inspect

Co-authored-by: Ben Toogood <ben@micro.mu>
2020-03-27 09:46:17 +00:00
b38da6ced0 api/handler/rpc: process all methods and merge url params to json body (#1427)
* api/handler/rpc: process all methods and merge url params to json body

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* add merge json test

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-27 07:59:31 +00:00
ben-toogood
1a53307a78 Remove debug auth logs (#1426)
Co-authored-by: Ben Toogood <ben@micro.mu>
2020-03-26 19:00:24 +00:00
Asim Aslam
e204f3e2e8 Add metadata Get method (#1425) 2020-03-26 18:50:00 +00:00
ben-toogood
329bd09f93 Fix Auth Init bug (#1424)
Co-authored-by: Ben Toogood <ben@micro.mu>
2020-03-26 18:09:51 +00:00
ben-toogood
4648fd0d09 Auth debugging (#1423)
* More auth debugging

* More auth debugging

* Increase auth debugging

Co-authored-by: Ben Toogood <ben@micro.mu>
2020-03-26 17:55:35 +00:00
ben-toogood
c905df3be6 Log auth verify requests (#1422)
* More auth debugging

* More auth debugging

Co-authored-by: Ben Toogood <ben@micro.mu>
2020-03-26 17:35:28 +00:00
Asim Aslam
62f9a054a4 100mb (#1421) 2020-03-26 16:57:31 +00:00
ben-toogood
00e7804f96 Auth - Add debugging to loading rules (#1420)
* Fix auth multi-rule edgecase

* Add logging to auth rules

Co-authored-by: Ben Toogood <ben@micro.mu>
2020-03-26 16:30:31 +00:00
ben-toogood
42b6bf5bbf Fix auth multi-rule edgecase (#1418)
Co-authored-by: Ben Toogood <ben@micro.mu>
2020-03-26 15:52:48 +00:00
ben-toogood
844c456839 Refactor Auth Service Protos, Add Access Rules (#1411)
* Refactor auth/service into two protos

* Accounts Proto

* Store Prefixes

* Misc

* Tweak Protos

Co-authored-by: Ben Toogood <ben@micro.mu>
Co-authored-by: Asim Aslam <asim@aslam.me>
2020-03-26 13:12:43 +00:00
Asim Aslam
7182ca1fd0 fix server logging (#1417) 2020-03-26 13:08:06 +00:00
02839cfba5 api/handler: use http.MaxBytesReader and buffer pool (#1415)
* api/handler: use http.MaxBytesReader

protect api handlers from OOM cases

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-26 14:29:28 +03:00
Asim Aslam
776a7d6cd6 Update filter comment for proxy (#1416) 2020-03-26 08:05:00 +00:00
beaa434610 logger: fix reading env var (#1414)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-25 22:00:43 +00:00
Asim Aslam
6efc5556e5 use requested service (#1413) 2020-03-25 20:59:37 +00:00
Asim Aslam
8d0826a031 Add check for k8s condition (#1412) 2020-03-25 19:32:41 +00:00
ben-toogood
378d03eb66 Tidying up auth (#1410)
* Don't clear auth rules if request fails

* Add jitter to auth service loading rules

* Remove unused error from ContextWithToken result

Co-authored-by: Ben Toogood <ben@micro.mu>
2020-03-25 18:34:13 +00:00
ben-toogood
56af826230 Update auth to pass seconds and not nanoseconds (#1409)
Co-authored-by: Ben Toogood <ben@micro.mu>
2020-03-25 17:03:45 +00:00
ben-toogood
511ebd8ec2 Fix Token Expiry Bug (#1408)
Co-authored-by: Ben Toogood <ben@micro.mu>
2020-03-25 14:40:37 +00:00
ben-toogood
1057ef6acb Add ContextWithToken (#1407)
* Add ContextWithToken

* Tidying up BearerScheme

Co-authored-by: Ben Toogood <ben@micro.mu>
2020-03-25 11:20:53 +00:00
ben-toogood
35e2a68a98 Fix auth bug restricting access to unauthorised endpoints (#1405)
Co-authored-by: Ben Toogood <ben@micro.mu>
2020-03-25 10:31:33 +00:00
ben-toogood
0e56382107 Fix service level auth, add improved error descriptions to aid with debugging (#1403)
Co-authored-by: Ben Toogood <ben@micro.mu>
2020-03-25 09:35:29 +00:00
Jake Sanders
dff98355be Missing ; in SQL query 2020-03-24 23:49:09 +00:00
8100d26430 api/router/registry: use logger (#1402)
* api/router/registry: use logger

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* api/server/acme: use logger

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-24 20:45:11 +00:00
Jake Sanders
397a8638f4 Cockroach Store bugfix (#1401) 2020-03-24 17:16:38 +00:00
Jake Sanders
eb4d2ae6aa Remove useless variable from cockroach store (#1400) 2020-03-24 15:37:30 +00:00
Jake Sanders
914340585c Trim space from env variables (#1399) 2020-03-24 14:51:43 +00:00
ben-toogood
84b4eb5404 Fix missing loop (#1398)
* WithRoles variadic args

* Load Rules

* Timer => Ticker

* Add missing for loop in auth service

Co-authored-by: Ben Toogood <ben@micro.mu>
2020-03-24 14:16:57 +00:00
ben-toogood
fd664f4392 Auth load rules (#1397)
* WithRoles variadic args

* Load Rules

* Timer => Ticker

Co-authored-by: Ben Toogood <ben@micro.mu>
2020-03-24 13:48:37 +00:00
ben-toogood
86272a3064 WithRoles variadic args (#1395)
Co-authored-by: Ben Toogood <ben@micro.mu>
2020-03-24 10:18:34 +00:00
ben-toogood
c1978265ab Auth Wildcard Endpoints (#1394)
* Auth Wildcard Endpoints

* Fix joinkey bug, improve tests

* Change joinKey

Co-authored-by: Ben Toogood <ben@micro.mu>
2020-03-24 09:39:33 +00:00
ben-toogood
e0e77f3983 Updated auth interface (#1384)
* Updated  auth interface

* Add Rule

* Remove Rule

* Return token from Renew

* Renew => Refresh

* Implement Tokens & Default Auth Implementation

* Change default auth to noop

* Change default auth to noop

* Move token.Token to auth.Token

* Remove Token from Account

* Auth service implementation

* Decode JWT locally

* Cookie for secret

* Move string to bottom of interface definition

* Depricate auth_exclude

* Update auth wrappers

* Update go.sum

Co-authored-by: Ben Toogood <ben@micro.mu>
2020-03-23 16:19:30 +00:00
9826ddbd64 api/handler/rpc: log errors (#1390)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-23 10:31:35 +03:00
0987363
87617be227 Add client header to rpcRequest header; issue #957 (#1378)
Co-authored-by: Asim Aslam <asim@aslam.me>
2020-03-21 23:25:23 +00:00
d559587807 client/grpc: remove json-iterator usage (#1387)
* minimize external deps and binary size
* if user wants json-iterator codec it must be used in server and
  client code. so best to use it via go-plugins

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-21 09:40:58 +00:00
Janos Dobronszki
9501512219 Auth util func RequestToContext (#1386) 2020-03-20 15:23:12 +00:00
Asim Aslam
d2f153d795 Add type of service (#1385) 2020-03-20 12:48:12 +00:00
Asim Aslam
e49be1da42 fix local runtime (#1383) 2020-03-19 22:38:37 +00:00
Jake Sanders
4c6f68d537 Implement store read cache (#1366)
* Implement store read cache

* Added cache tests and fixed a bug in memory store
2020-03-19 18:19:07 +00:00
cbb958def5 config: fix panic on multiple Close() (#1374)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-19 12:54:59 +03:00
Asim Aslam
40ff6ddfcf sigh, further status changes (#1371) 2020-03-18 22:47:03 +00:00
Asim Aslam
5ad7c36bd4 Fix labels for k8s (#1370) 2020-03-18 22:13:21 +00:00
Asim Aslam
99c3fe2bb8 fix status parsing (#1368) 2020-03-18 21:50:52 +00:00
Asim Aslam
1bd340701b add k8s service ip to metadata (#1367)
* add k8s service ip to metadata

* go fmt

* use same port as container
2020-03-18 18:27:29 +00:00
Jake Sanders
c91bf7e9e7 [WIP] Store Sync (#1365)
* Initial cache implementation

* Write queue implementation

* Accidentally started writing the storage sync service
2020-03-18 16:39:36 +00:00
41f8a8cb00 errors: add FromError func (#1362)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-18 03:10:38 +03:00
ben-toogood
cd04111e3d Pass redirect_to param on auth (#1361)
Co-authored-by: Ben Toogood <ben@micro.mu>
2020-03-17 20:04:16 +00:00
ben-toogood
00cd2448a4 Fix bug where auth token is not set from cookie when excluded endpoint (#1360)
Co-authored-by: Ben Toogood <ben@micro.mu>
2020-03-17 19:24:10 +00:00
ben-toogood
8a41d369f2 Auth JWT ID Fix (#1359)
* Auth JWT ID Fix

* Remove unused ID in jwt claims

Co-authored-by: Ben Toogood <ben@micro.mu>
2020-03-17 16:59:57 +00:00
Jake Sanders
638c219736 Cockroach store feature completion (#1358)
* Start fixing cockroach store

* Add prefix, suffix, limit, offset for cockroachdb store
2020-03-17 16:15:23 +00:00
ben-toogood
b3c631dd38 Support Wildcard Auth Excludes (#1357)
Co-authored-by: Ben Toogood <ben@micro.mu>
2020-03-17 16:03:49 +00:00
ab73127063 grpc client/server fixes (#1355)
* grpc client/server fixes

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-17 14:27:20 +03:00
Asim Aslam
03031a694d use pod phase/status (#1356) 2020-03-16 23:47:34 +00:00
li.peng
5712aafba9 fix: context cancel (#1350)
Co-authored-by: Asim Aslam <asim@aslam.me>
2020-03-16 10:45:33 +00:00
ac333d9d47 client/grpc: unwrap error after call (#1352)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-16 13:33:38 +03:00
ben-toogood
247707f583 Return store.ErrNotFound if not found when calling over rpc (#1353)
Co-authored-by: Ben Toogood <ben@micro.mu>
2020-03-16 10:30:56 +00:00
ben-toogood
d91c14eb30 grpc client error fix (#1351)
Co-authored-by: Ben Toogood <ben@micro.mu>
2020-03-16 12:53:15 +03:00
Asim Aslam
ca8684a886 fix k8s issues (#1349) 2020-03-15 15:09:18 +00:00
Asim Aslam
0449138f61 fix panic (#1348) 2020-03-14 21:18:41 +00:00
609f4826b3 server: remove duplicate code (#1346)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-13 22:15:09 +00:00
60993e6275 config/source/service: base64 fix (#1345)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-13 21:44:55 +00:00
Asim Aslam
e803fb0855 Runtime hacks (#1344)
* Add Args/Image to runtime

* remove the hacks
2020-03-13 18:39:59 +00:00
3543b275e0 fix log level helper (#1342)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-13 17:36:42 +03:00
fbde872e7f Revert "server/grpc: fix ordering of register and check for registered (#1338)" (#1341)
This reverts commit 62a644ddd8.
2020-03-13 09:30:44 +00:00
Asim Aslam
078dd4eb9b fix etcd (#1340)
* fix etcd

* update go mod
2020-03-13 08:55:23 +00:00
62a644ddd8 server/grpc: fix ordering of register and check for registered (#1338)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-12 22:04:11 +00:00
Asim Aslam
d8cfa7a295 add config to cmd (#1337)
* add config to cmd

* fix build
2020-03-12 18:47:40 +00:00
ben-toogood
47f1203e97 Add Config to service options (#1336)
Co-authored-by: Ben Toogood <ben@micro.mu>
Co-authored-by: Asim Aslam <asim@aslam.me>
2020-03-12 18:13:03 +00:00
Jake Sanders
1b4e881d74 Rewrite the store interface (#1335)
* WIP store rewrite

* Fix memory store tests

* Store hard expiry times rather than duration!

* Clarify memory test

* Add limit to store interface

* Implement suffix option

* Don't return nils from noop store

* Fix syncmap

* Start fixing store service

* wip service and cache

* Use _ for special characters in cockroachdb namespace

* Improve cockroach namespace comment

* Use service name as default store namespace

* Fixes

* Implement Store Scope

* Start fixing etcd

* implement read and write with expiry and prefix

* Fix etcd tests

* Fix cockroach store

* Fix cloudflare interface

* Fix certmagic / cloudflare store

* comment lint

* cache isn't implemented yet

* Only prepare DB staements once

Co-authored-by: Ben Toogood <ben@micro.mu>
Co-authored-by: ben-toogood <bentoogood@gmail.com>
2020-03-12 13:41:30 +00:00
ben-toogood
20ce61da5a Oauth google fixes (#1330)
* Fix Auth Headers

* Tweak Oauth to work for Google

Co-authored-by: Ben Toogood <ben@micro.mu>
Co-authored-by: Asim Aslam <asim@aslam.me>
2020-03-12 13:11:35 +00:00
chengguoqiang
eef4825be4 Update etcd.go (#1334)
add leaseId to the trace log
2020-03-12 10:09:38 +00:00
Asim Aslam
be9c6141f5 delete options (#1333) 2020-03-12 09:05:09 +00:00
Asim Aslam
1ca4619506 return store.ErrNotFound (#1332) 2020-03-11 23:09:42 +00:00
Asim Aslam
f55493993c set namespace rather than key (#1331) 2020-03-11 22:31:24 +00:00
7b385bf163 minimize allocations in logger and tunnel code (#1323)
* logs alloc

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* fix allocs

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* fix allocs

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* tunnel allocs

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* try to fix tunnel

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* cache cipher for send

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* more logger

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* more logger

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* more logger

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* more logger

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* more logger

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* more logger

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* more logger

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-11 17:55:39 +00:00
Jake Sanders
4125ae8d53 Add secrets interface to config/secrets (#1325)
* Interface for secrets

* Add secretbox secrets implementation

* Start working on box

* typo

* Add asymmetric encryption implementation

* go mod tidy

* Fix review comments

Co-authored-by: Asim Aslam <asim@aslam.me>
2020-03-10 22:52:06 +00:00
ben-toogood
48b2a5c37c Fix Auth Headers (#1324)
Co-authored-by: Ben Toogood <ben@micro.mu>
2020-03-10 16:47:01 +00:00
Asim Aslam
ed83c27f0e add websocket streaming to api rpc handler (#1326) 2020-03-10 15:21:43 +00:00
241614ff68 add helper function to determine logger level (#1321)
* add helper function to determine logger level

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-09 23:43:05 +03:00
mlboy
1a4f608ed1 add: auth add generate options Expiry for set token expires (#1319)
Co-authored-by: mlboy <ml3@meitu.com>
Co-authored-by: Asim Aslam <asim@aslam.me>
2020-03-09 17:16:31 +00:00
43b0dbb123 tunnel: reduce allocation and improve performance (#1320)
* tunnel: reduce allocation and improve performance

BenchmarkSha256Old-16 100000 156748 ns/op 11835 B/op 168 allocs/op
BenchmarkSha256Old-16 100000 156229 ns/op 11819 B/op 168 allocs/op

BenchmarkSha256New-16 100000 154751 ns/op 11107 B/op 161 allocs/op
BenchmarkSha256New-16 100000 154263 ns/op 11110 B/op 161 allocs/op

simple change lowers allocations and brings performance

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* fix

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* tunnel: reuse buf in Decrypt

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* fix unneeded conversations

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* base32 string is smaller than hex string

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-09 17:10:08 +00:00
ben-toogood
b344171c80 URL Encode Provider.Endpoint() (#1317)
Co-authored-by: Ben Toogood <ben@micro.mu>
2020-03-09 10:21:49 +00:00
ben-toogood
e3ce45495a os.Exit on log.Fatal (#1316)
* os.Exit on log.Fatal

* Fix TestOptions

Co-authored-by: Ben Toogood <ben@micro.mu>
2020-03-09 09:23:42 +00:00
f01664a551 Merge pull request #1313 from micro/upstream
fix ipv6 address usage in mdns registry and util/addr
2020-03-07 23:50:03 +03:00
8ecbdc1cd6 registry/mdns: add logging for invalid endpoint
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-07 23:19:48 +03:00
55c19afb0b registry/mdns: fix ipv6 addr in mdns registry
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-07 23:17:00 +03:00
077063c212 util/addr: check ip addrs before return
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-07 23:13:56 +03:00
ben-toogood
9a7a65f05e Auth Provider (#1309)
* auth provider mock interface

* Auth Provider Options

* Implement API Server Auth Package

* Add weh utils

* Add Login URL

* Auth Provider Options

* Add auth provider scope and setting token in cookie

* Remove auth_login_url flag

Co-authored-by: Asim Aslam <asim@aslam.me>
Co-authored-by: Ben Toogood <ben@micro.mu>
2020-03-07 11:06:57 +00:00
8ee5607254 [WIP]: broker ErrorHandler option (#1296)
* broker ErrorHandler option

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* rewrite Event interface, add error

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* implement new interface

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* change ErrorHandler func to broker.Handler

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* fix

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-06 21:25:16 +00:00
11be2c68b9 util/stream: fix imports (#1310)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-06 21:17:57 +00:00
a864f812f1 web: fix ipv6 address issue (#1308)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-06 18:44:56 +03:00
Asim Aslam
ae60bea8d8 add stream fix (#1305) 2020-03-06 14:40:47 +00:00
Jake Sanders
a851b9db7a Comment typo in gRPC subscriber (#1304) 2020-03-05 14:55:46 +00:00
d807dac2a7 server/grpc: avoid panic in case of nil Header (#1303)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-05 17:45:31 +03:00
ce2ba71002 server: subscribe to topic with own name if router not nil (#1295)
* server: subscribe to topic with own name if router not nil

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-05 10:29:50 +03:00
Asim Aslam
67c26c71b6 add jitter (#1298) 2020-03-04 15:37:17 +00:00
ben-toogood
9386f36a13 Exit on log.Fatal (#1297) 2020-03-04 13:46:01 +00:00
ben-toogood
6d803d9e45 Implement api/server/cors (#1294) 2020-03-04 11:40:53 +00:00
ben-toogood
6a9001bdb1 Set auth account in context (#1293) 2020-03-04 09:54:52 +00:00
Jake Sanders
3f0c28a815 Expiration is actually a unix timestamp (#1290)
* Expiration is actually a unix timestamp

* int -> int64
2020-03-03 18:15:50 +00:00
Asim Aslam
49ffc60afb Use Foo.Call on /foo (#1286)
Co-authored-by: Jake Sanders <i@am.so-aweso.me>
2020-03-03 16:47:15 +00:00
Jake Sanders
beb5e80e87 Fix nil pointer dereference (#1289) 2020-03-03 13:54:56 +00:00
Jake Sanders
eebd69c995 Change from renekroon/ttlcache to patrickmn/go-cache (#1288) 2020-03-03 13:35:49 +00:00
Jake Sanders
bc71989e2c int64 -> time.Duration (#1287) 2020-03-03 13:15:26 +00:00
89ba602e17 logger fixes and improvements (#1285)
* fix helper fields
* add metadata output for default logger

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-03 11:07:37 +03:00
Jake Sanders
f6102bde70 Add a cache to workers KV storage implementation (#1284)
* cloudflare-cache

* go mod tidy
2020-03-02 18:14:25 +00:00
Pieter Voorwinden
7cad77bfc0 Initialize header to prevent assignment to entry in nil map error (#1282)
Co-authored-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-02 19:17:26 +03:00
ben-toogood
1f2e067f71 k8s runtime - get status from pods (#1283) 2020-03-02 15:49:10 +00:00
b555269b1b copy fields in helper (#1281)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-03-02 14:18:36 +00:00
ben-toogood
9200c70202 Replace validation error with regex for cockroach namespace (#1270)
Co-authored-by: Asim Aslam <asim@aslam.me>
2020-03-01 22:09:06 +00:00
Sumanth Chinthagunta
d8377e09c9 feat(dockerfile): adding dumb-init to base image (#1278) 2020-02-29 21:55:15 +00:00
0754229878 broker/memory: add codec support (#1276)
allow easy testing of other services with memory broker
and also allows to more deeply simulate real brokers

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-02-29 23:00:29 +03:00
6b8930a960 add new helper method to logger (#1273)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-02-29 00:39:41 +00:00
d0a978bd50 redesign logger (#1272)
* redesign logger

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-02-29 03:31:59 +03:00
ben-toogood
afe6861e2f Update the k8s deployment to use metadata labels & custom source (#1271) 2020-02-28 15:07:55 +00:00
ben-toogood
962567ef42 Implement config singleton (#1268)
* Implement config singleton

* Pass token in grpc request headers

* Refactor BearerScheme

* Fix typo
2020-02-28 12:58:27 +00:00
Asim Aslam
e21ed3a183 gen account on base32 decode failure (#1269) 2020-02-27 16:11:05 +00:00
64a5ce9607 various fixes (#1267)
* logger: remove Panic log level

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* server/grpc: add missing Unlock in Subscribe error

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* server: minor code change

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* server/grpc: extend test suite with pub/sub testing

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* server/grpc: fix invalid check and allow subscriber error to be returned

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* server/grpc: add pubsub tests

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* client/grpc: check for nil req/rsp

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-02-26 18:34:40 +00:00
Asim Aslam
d651b16acd generate pseudo accounts (#1264)
* generate pseudo accounts

* when you think you're being clever

* return garbage pseudo account when no token
2020-02-26 13:42:32 +00:00
Eric
1034837f69 Adjusting the BeforeStart () position (#1263)
Co-authored-by: Asim Aslam <asim@aslam.me>
2020-02-26 11:44:10 +03:00
Lars Lehtonen
80f2bfd5d0 config: remove unused sep variable (#1262) 2020-02-26 08:25:33 +00:00
Asim Aslam
6aaaf54275 add MICRO_AUTH_TOKEN, parse token in wrapper, preload config and othe… (#1261)
* add MICRO_AUTH_TOKEN, parse token in wrapper, preload config and other things

* fix wrapper panic
2020-02-25 22:15:44 +00:00
Di Wu
603d37b135 Set option and cli args to the service profile (#1259) 2020-02-25 16:42:42 +00:00
Eric
53c3bff819 add Panic & Panicf to logger (#1258)
* add Panic & Panicf to logger
2020-02-25 17:44:29 +03:00
ben-toogood
dcf859098b Fix k8s commands for github (#1257) 2020-02-25 11:39:03 +00:00
b4a743898e fix router panic (#1254)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-02-24 23:15:59 +00:00
ben-toogood
f1e7ea3020 Handle non IsNotExist errors in config (#1251)
Co-authored-by: Asim Aslam <asim@aslam.me>
2020-02-24 18:07:11 +00:00
ben-toogood
5e8d5834eb Dynamic Runtime source for k8s with github packages (#1252)
* Dynamic Runtime source for k8s

* Still check for source

* Replace / with - for k8s service names

* Simplify sourceForName function
2020-02-24 17:47:47 +00:00
ben-toogood
ffdf986aac Refactor auth: add token and store implementations (#1230)
* Refactor auth: add token and memory implementations

* Fix typo

* Remove memory auth (implemented already by the store implementation), revert default to noop

* Add grpc header

* Global Config

* config/global => util/config

* Rename package to remove confict

* Tweak

* Improve Error Handling
2020-02-24 15:07:27 +00:00
Jake Sanders
56f8115ea8 Rename PR job (#1250) 2020-02-24 14:16:51 +00:00
5b0175c2e5 allocations improvements and tunnel fixes (#1248)
* reduce allocations in tunnel code

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* another allocation fix

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* allocate maps with len if it known

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* allocate key for send once

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-02-24 14:15:20 +00:00
Jake Sanders
01d88601c0 Split PR and merge tests (#1249) 2020-02-24 14:11:17 +00:00
Lars Lehtonen
d467236f8f broker/nats: remove unused setPublishOption() (#1234)
broker/nats: remove unused setSubscribeOption()
2020-02-24 13:49:27 +00:00
24d574ae71 server/grpc: add MaxConn option to limit max inflight requests (#1247)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-02-24 13:48:56 +00:00
cf0b39eaac logger fixes (#1244)
* logger: fix race conditions

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* restore util/log for compatibility

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-02-24 13:07:40 +00:00
1f767ba18c update go modules (#1240)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-02-23 20:47:44 +00:00
Asim Aslam
915c424213 Add docker build (#1239) 2020-02-23 15:57:21 +00:00
117f56ebf7 prune util/log and user logger (#1237)
* prune util/log and user logger

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* plaintext logger

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* add newline

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-02-23 13:45:20 +00:00
Gao.QiLin
ceed8942fc Update README.md change godoc => go.dev (#1236)
* Update README.md add go dev

* Update README.zh-cn.md add go dev
2020-02-22 08:56:42 +00:00
d1e25e7ead add metadata set method (#1232)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-02-21 23:04:47 +03:00
Jake Sanders
7e24c0c1cf Also run tests on PR (#1233) 2020-02-21 17:57:07 +00:00
Jake Sanders
ca251ba111 Switch from Travis CI to GitHub Actions (#1231)
* Create Github Action to run tests on push

* -v

* Update tests.yml

* TODO: Fix tests

* Fix colours

* Delete .travis.yml

* Update tests.yml

* builds -> build
2020-02-21 17:43:50 +00:00
Asim Aslam
116855572b Add log level helper funtions (#1229) 2020-02-21 08:43:23 +00:00
Asim Aslam
ee977acfef strip SetGlobalLevel (#1228) 2020-02-21 08:28:21 +00:00
Sumanth Chinthagunta
3fa7c26946 logger with helper methods (#1216)
* support unix daemon socket

* refactor(logger): logger fields changed to map[string]interface{}

* improvement(logger): adding string to Level Parser

* improvement(logger): rename ParseLevel to GetLevel

* refactor(logger): adding basic logger

adding micro default logger, and refactor logger interface

* refactor(logger): moved basic logger to top level package

* refactor(logger): adding default logger
2020-02-21 07:57:59 +00:00
Lars Lehtonen
88457b812e tunnel: Prune Unused Functions (#1224)
* tunnel: remove unused link.setLoopback()

* tunnel: remove unused link.accept()

* tunnel: remove unused link.connect()
2020-02-20 17:05:49 +00:00
Asim Aslam
78df154a4d move log level setting to option (#1222) 2020-02-20 08:26:12 +00:00
Lars Lehtonen
c7eed618c2 server/grpc: Prune Unused Code (#1220)
* server/grpc: remove unused grpcServer.newCodec()

* server/grpc: remove unused defaultRPCCodecs
2020-02-19 20:58:22 +00:00
ben-toogood
36bcd3bd82 Improve JWT Package Errors (#1206)
Co-authored-by: Asim Aslam <asim@aslam.me>
2020-02-19 09:51:43 +01:00
Asim Aslam
f4118dc357 secure the grpc client (#1215)
* secure the grpc client

* make compile

* Add system cert pool

* Revert manually adding ca certs

* Tweak comment

Co-authored-by: ben-toogood <bentoogood@gmail.com>
2020-02-19 08:44:35 +00:00
58598d0fe0 fixes for safe conversation and avoid panics (#1213)
* fixes for safe convertation

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* fix client publish panic

If broker connect returns error we dont check it status and use
it later to publish message, mostly this is unexpected because
broker connection failed and we cant use it.
Also proposed solution have benefit - we flag connection status
only when we have succeseful broker connection

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* api/handler/broker: fix possible broker publish panic

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-02-18 23:05:38 +00:00
6248f05f74 add missing option to client.NewMessage (#1212)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-02-18 14:18:59 +03:00
ben-toogood
aa9a0a8d23 Fix Micro Proxy nil Transport Bug (#1208) 2020-02-17 12:28:48 +03:00
ben-toogood
1e40c86dfe Ignore gRPC Proxy (#1205) 2020-02-17 08:14:45 +00:00
Asim Aslam
9696efde02 reorder auth interface (#1204) 2020-02-16 19:36:45 +00:00
Asim Aslam
b3fc8be24e normalise proxy name (#1203) 2020-02-15 21:57:30 +00:00
Sumanth Chinthagunta
fc5339a368 [W.I.P] refactor(logger): logger fields changed to map[string]interface{} (#1198)
* support unix daemon socket

* refactor(logger): logger fields changed to map[string]interface{}

* improvement(logger): adding string to Level Parser

* improvement(logger): rename ParseLevel to GetLevel
2020-02-15 18:19:28 +00:00
Asim Aslam
964b7dee3f add tls config to server (#1202)
* add tls config

* add TLSConfig to acme provider
2020-02-15 15:10:26 +00:00
Asim Aslam
158949d0d0 accept Listen option in grpc server (#1201) 2020-02-15 14:09:24 +00:00
Asim Aslam
eed8a0bf50 delete proxy cached route before updating (#1200) 2020-02-15 12:05:22 +00:00
Asim Aslam
c691d116ab when the stream errors cleanup the connection (#1199) 2020-02-15 11:35:08 +00:00
Eric
cbe8b7dd09 Removed redundant spaces (#1196) 2020-02-14 10:32:02 +03:00
Asim Aslam
203486fd31 check for etcd watcher canceled value 2020-02-13 22:34:56 +00:00
Asim Aslam
d9b3b17582 set dial timeout in stream 2020-02-13 18:51:32 +00:00
ben-toogood
e080ecb43a Auth Improvements (#1195)
* Exclude Stats & Trace from Auth

* Update Excluded Endpoints Format

* Tweak Implementation
2020-02-13 14:07:14 +00:00
ben-toogood
ea70711dd3 Exclude Stats & Trace from Auth (#1192) 2020-02-13 12:02:29 +00:00
6dc942bc19 client/grpc: fix panic on invalid message (#1191)
* client/grpc: fix panic on invalid message
* travis: disable lint and race for now

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-02-13 14:57:21 +03:00
Janos Dobronszki
d76baf59de Trace type is now being recorded (#1188) 2020-02-12 10:57:17 +00:00
79ad1e6fe3 various fixes for broker and messaging in server (#1187)
* provide broker disconnect messages in server

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* broker/eats: another fix

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-02-11 18:41:23 +00:00
2764de9a1a broker/eats: broker disconnect fix (#1186)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-02-11 15:46:50 +00:00
Asim Aslam
d1d6eada98 parse url encoded form in rpc handler (#1183)
* parse url encoded form in rpc handler

* Remove comment
2020-02-11 11:27:16 +00:00
ben-toogood
4a03183481 Return a 401 error on invalid auth tokens (#1184) 2020-02-11 11:22:22 +00:00
Asim Aslam
8ea84ac3eb Fix router panic for nil watcher 2020-02-10 15:38:41 +00:00
ben-toogood
4401c12e6c Auth Wrapper (#1174)
* Auth Wrapper

* Tweak cmd flag

* auth_excludes => auth_exclude

* Make Auth.Excludes variadic

* Use metadata.Get (passes through http and http2 it will go through various case formats)

* fix auth wrapper auth.Auth interface initialisation

Co-authored-by: Asim Aslam <asim@aslam.me>
2020-02-10 08:26:28 +00:00
c706afcf04 logger helper to pass down it via context (#1180)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-02-09 21:26:46 +00:00
Lars Lehtonen
ca1d0b94c3 config/cmd: remove 8 unused variables (#1175) 2020-02-08 11:19:10 +00:00
67acd9288b config/source/cli: fix tests (#1179)
* config/source/cli: fix tests
* skip mdns test in travis

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-02-08 02:45:32 +03:00
0bf6c9fc08 config/source/cli: fix default flag value loading (#1178)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-02-08 02:14:34 +03:00
99807a680c strip Micro-Topic header from incoming context in client.Call (#1177)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-02-07 22:09:52 +00:00
f0f7f860d6 add some docs (#1176)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-02-07 21:48:24 +00:00
Asim Aslam
ef537270ad Don't store traces for Debug endpoints 2020-02-07 20:58:03 +00:00
Asim Aslam
c7f075d157 rename file 2020-02-07 14:00:27 +00:00
Asim Aslam
812ea78604 Fix runtime deadlock 2020-02-07 14:00:09 +00:00
Asim Aslam
0755084a59 fix deadlock 2020-02-07 13:55:55 +00:00
ben-toogood
fe7f5a4134 Runtime Retries Limit (#1163)
* Implement Runtime Retries

* Remove Debug

* Action Feedback

* Refactor Retries

* Fix WithRetires Typo
2020-02-07 12:02:41 +00:00
ben-toogood
19c454ec4b Fix Local Runtime Default Command (#1173)
* Auth API Proto

* Fix local runtime bug

* Add Platform Proto

* Restructuring
2020-02-07 11:39:26 +00:00
Asim Aslam
0e9b4c26a4 import with braces 2020-02-06 21:39:08 +00:00
Asim Aslam
d40b13a045 mux to mtx 2020-02-06 21:37:17 +00:00
Asim Aslam
4079b22c1e reorder logger methods 2020-02-06 21:36:33 +00:00
Shu xian
fdfb2bc4c1 [WIP] logger first (#1161)
* logger first

* log->logger

* update comment

* add context in Options

* add Fields

* remove logfi

* add field encode

* add common Field Types

* update logger field
2020-02-06 21:35:46 +00:00
Asim Aslam
dbeb7cfe9c remove errors import 2020-02-06 18:45:12 +00:00
Asim Aslam
512df2628f trim source url if its set to github.com/ 2020-02-06 18:34:16 +00:00
Janos Dobronszki
92571db693 Tracing: traces now correctly form a tree (#1170)
* First cut of trace

* Dial it back yo

* Defensive programming
2020-02-06 17:22:16 +00:00
ben-toogood
16552620e0 Runtime Custom Source (Part 2) (#1169) 2020-02-06 16:16:01 +00:00
Ben Toogood
5414195dc3 Add Args 2020-02-06 12:31:54 +00:00
Ben Toogood
0591760932 Arg => Args 2020-02-06 12:17:16 +00:00
Ben Toogood
48b9f3f5e9 Fix 2020-02-06 11:28:34 +00:00
Ben Toogood
e46278a766 Test 2020-02-06 11:24:56 +00:00
Ben Toogood
2925b1615c Fix 2020-02-06 11:15:30 +00:00
Ben Toogood
fc4191c647 Fix 2020-02-06 11:12:40 +00:00
Ben Toogood
111126c780 Debugging 2020-02-06 11:00:14 +00:00
Ben Toogood
54371bba6a Debugging 2020-02-06 10:55:41 +00:00
Ben Toogood
c28737e88e Debugging 2020-02-06 10:54:11 +00:00
Ben Toogood
c7d922fac2 Debugging 2020-02-06 10:49:01 +00:00
Ben Toogood
f8e696bd30 Debugging 2020-02-06 10:44:12 +00:00
Ben Toogood
6aef28dad2 Runtime set service source 2020-02-06 10:33:23 +00:00
7105e4099c pass micro errors from grpc server to grpc client (#1167)
* pass micro errors from grpc server to grpc client

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>

* wrap micro errors.Error to grpc status

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-02-06 10:18:33 +00:00
Ben Toogood
f0762bbb6b Improve Logging 2020-02-06 10:16:32 +00:00
Ben Toogood
243c6a4246 Debug 2020-02-06 10:08:56 +00:00
Ben Toogood
9983aea928 Tidying Up 2020-02-06 09:29:27 +00:00
Ben Toogood
aa58a9749b Action Asim's Feedback 2020-02-06 09:17:10 +00:00
ben-toogood
d8110b70a3 Runtime custom docker img (#1168)
* Add DeploymentOptions to K8s Client

* WithBaseImage for  Runtime

* Revert Change

* Fix sequencing
2020-02-06 08:52:25 +00:00
a44dc90d45 fix ctx.Done issue #720 (#1166)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-02-05 21:13:14 +00:00
Shu xian
12181bd441 fix LevelInfo > LevelWarn (#1162) 2020-02-05 18:16:57 +00:00
Ben Toogood
8d44f7226f Merge branch 'master' of https://github.com/micro/go-micro 2020-02-05 13:59:51 +00:00
ben-toogood
bf747a86f4 Runtime (#1160)
* Add String to Runtime interface

* Setup Dynamic Runtime Configuration
2020-02-05 13:59:35 +00:00
Lars Lehtonen
4333f00a43 runtime/kubernetes: remove unused constants (#1159) 2020-02-04 21:02:05 +00:00
7ab3a31ac4 update micro/cli, tidy mod (#1156)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-02-03 23:29:44 +00:00
Ben Toogood
a1d5d6831f Add String to Runtime interface 2020-02-03 15:56:16 +00:00
ben-toogood
1b9cabd654 Update Micro Auth Protocol Buffer to use V2 (#1155) 2020-02-03 08:26:57 +00:00
ben-toogood
d621548120 Auth (#1147)
Implement the Auth interface, with JWT and service implementations.

* Update Auth Interface

* Define Auth Service Implementation

* Support Service Auth

* Add Auth Service Proto

* Remove erronious files

* Implement Auth Service Package

* Update Auth Interface

* Update Auth Interface. Add Validate, remove Add/Remove roles

* Make Revoke interface more explicit

* Refactor serializing and deserializing service accounts

* Fix srv name & update interface to be more explicit

* Require jwt public key for auth

* Rename Variables (Resource.ID => Resource.Name & ServiceAccount => Account)

* Implement JWT Auth Package

* Remove parent, add ID

* Update auth imports to v2. Add String() to auth interface
2020-02-03 08:16:02 +00:00
tpam28
449bcb46fe New backoff (#1153)
* new backoff function

* use backoff from util/backoff

* remove reset atemts

* change comment

* fmt
2020-02-02 20:32:55 +00:00
Asim Aslam
079102ea59 Merge branch 'master' of ssh://github.com/micro/go-micro 2020-02-02 19:50:09 +00:00
Asim Aslam
a9d371e727 fatal on command error 2020-02-02 19:49:59 +00:00
Asim Aslam
27efbc8779 Merge pull request #1150 from unistack-org/grpc_race
fix map race condition in grpc server
2020-02-01 00:10:46 +00:00
efb59d9709 fix map race condition in grpc server
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-02-01 02:52:53 +03:00
Asim Aslam
003f00b483 Merge branch 'master' of ssh://github.com/micro/go-micro 2020-01-30 23:24:54 +00:00
Asim Aslam
0be22c98c6 add tracing 2020-01-30 23:24:46 +00:00
Asim Aslam
bafedf1aad Merge pull request #1149 from alrs/remove-unused-kubernetes-variable
runtime/kubernetes: remove unused name variable
2020-01-30 17:30:43 +00:00
Lars Lehtonen
98d55545fd runtime/kubernetes: remove unused name variable 2020-01-30 09:25:50 -08:00
Asim Aslam
5f6271b044 Merge pull request #1148 from tpam28/master
fix test and description
2020-01-30 17:09:41 +00:00
Evgeniy
87753ad289 format results in TestBacloff 2020-01-30 20:08:03 +03:00
Evgeniy
ffb9da0230 fix test and description 2020-01-30 19:43:03 +03:00
Asim Aslam
50ac642666 Merge pull request #1146 from tpam28/master
exponentialBackoff was changed from power function to exponential
2020-01-30 14:35:17 +00:00
Evgeniy
f6fcfcb8fc exponentialBackoff was changed from power function to exponential function 2020-01-30 17:25:07 +03:00
Asim Aslam
21e0932339 Merge pull request #1144 from unistack-org/v2
fix import paths for v2 release
2020-01-30 11:46:29 +00:00
f23638c036 fix import paths for v2 release
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-01-30 14:44:40 +03:00
Asim Aslam
2b1e0a6fd6 go mod tidy 2020-01-30 10:33:40 +00:00
Asim Aslam
0889b814bb Merge pull request #1143 from crufter/bump-dep
Bump dep to fix platform web using new debug.Stats proto fields
2020-01-30 10:31:12 +00:00
Janos Dobronszki
a648c0d99c Bump dep to fix platform web using new debug.Stats proto fields 2020-01-30 10:27:21 +00:00
Asim Aslam
a291af59c4 Merge pull request #1142 from micro/tracing
Fix null tracer bug
2020-01-30 07:55:58 +00:00
Ben Toogood
d9f12731e1 Fix null tracer bug 2020-01-30 07:53:31 +00:00
Asim Aslam
4a838a8210 Merge branch 'master' of ssh://github.com/micro/go-micro 2020-01-29 23:14:16 +00:00
Asim Aslam
5969cc358e nats-e => eats 2020-01-29 23:14:05 +00:00
Asim Aslam
9f1a7e1139 Merge pull request #1127 from Allenxuxu/master
handle Loader.Load  return value error
2020-01-29 22:44:29 +00:00
Asim Aslam
dc257f5066 update to fix tracer 2020-01-29 22:43:40 +00:00
Asim Aslam
49b86c56e3 go fmt 2020-01-29 22:40:43 +00:00
Asim Aslam
1be8258721 fix initialisation 2020-01-29 22:39:31 +00:00
Asim Aslam
b2980aecb7 fix debug handler in proxy 2020-01-29 22:31:57 +00:00
Asim Aslam
de3c3b27b2 Merge pull request #1140 from micro/tracing
Tracing by Ben Toogood
2020-01-29 22:28:49 +00:00
Micro
a09eea8d4d Update the Debug Handler to use the servers tracer 2020-01-29 16:05:58 +00:00
Micro
62c067adcd Refactor debug/trace ready for Jaeger 2020-01-29 15:45:11 +00:00
Asim Aslam
59f6ca5564 Merge pull request #1139 from alrs/prune-unused-config-reader-func
config/reader/json: remove unused newValue()
2020-01-28 19:50:03 +00:00
Lars Lehtonen
895aa896bc config/reader/json: remove unused newValue() 2020-01-28 11:38:55 -08:00
Asim Aslam
74762edc42 Merge pull request #1138 from printfcoder/master
cockroach store supports URL connection string
2020-01-28 17:59:49 +00:00
shu xian
101017a29c cockroach supports URL connection string 2020-01-29 00:47:41 +08:00
Shu xian
c725b4c797 Merge pull request #3 from micro/master
merge
2020-01-29 00:45:27 +08:00
Asim Aslam
1108cc5e91 Merge pull request #1136 from unistack-org/flags
update micro/cli to urfave/cli/v2 and fix go-micro
2020-01-26 19:12:06 +00:00
Asim Aslam
6a9f5fac61 fire send in a go routine to prevent blocking other requests 2020-01-25 23:16:00 +00:00
e6a34bcbe7 update micro/cli to urfave/cli/v2 and fix go-micro
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-01-25 15:57:08 +03:00
Asim Aslam
1d00f2f771 add trace handler 2020-01-24 22:02:35 +00:00
Asim Aslam
4a6570a772 trace wrapper 2020-01-24 21:58:29 +00:00
Asim Aslam
a997a86e49 add trace context 2020-01-24 21:44:48 +00:00
Asim Aslam
2d28ff72d7 add trace 2020-01-24 21:32:07 +00:00
Asim Aslam
2b1844971c go fmt 2020-01-24 21:31:57 +00:00
Asim Aslam
49cc022ca2 add trace to handler 2020-01-24 21:29:29 +00:00
Asim Aslam
8d2dc8a822 trace Read endpoint 2020-01-24 21:24:51 +00:00
Asim Aslam
eeb6944ce5 Merge pull request #1133 from alrs/drop-unused-broker-code
broker: drop unused registryKey variable
2020-01-23 21:57:58 +00:00
Lars Lehtonen
add78f2967 broker: drop unused registryKey variable 2020-01-23 12:51:57 -08:00
Shu xian
bd6a5af2b5 Merge pull request #2 from micro/master
merge
2020-01-23 22:17:54 +08:00
Asim Aslam
ae08e9c106 check if event is nil 2020-01-23 12:41:22 +00:00
Asim Aslam
77c2a021da Add event id to router events 2020-01-23 11:44:06 +00:00
Asim Aslam
1c19678d04 Update proto Service => Config 2020-01-23 11:37:54 +00:00
Asim Aslam
6d636b7ab3 whoa bad commit, bad asim 2020-01-22 17:07:56 +00:00
Asim Aslam
009c598049 Change version to latest 2020-01-22 17:03:38 +00:00
Asim Aslam
5cceb00df2 Merge pull request #1131 from micro/router-refactor
refactor and cleanup some router code
2020-01-22 16:54:20 +00:00
Asim Aslam
3e24276eb1 fix break 2020-01-22 16:44:34 +00:00
Asim Aslam
29c1076950 refactor and cleanup some router code 2020-01-22 16:33:31 +00:00
Asim Aslam
8dbacb34f8 Merge pull request #1118 from printfcoder/master
add mucp for config/source
2020-01-21 22:35:35 +00:00
Asim Aslam
8b306780ee Merge pull request #1130 from micro/net-noloop
avoid connecting to self
2020-01-21 15:05:33 +00:00
Asim Aslam
9f7d374691 avoid connecting to self 2020-01-21 12:36:05 +00:00
Asim Aslam
a18e53f028 Merge branch 'master' of ssh://github.com/micro/go-micro 2020-01-20 21:31:16 +00:00
Asim Aslam
2208839027 Merge pull request #1129 from alrs/remove-unused-server-var
server: remove unused invalidRequest
2020-01-20 18:24:42 +00:00
Lars Lehtonen
7a17a221ff server: remove unused invalidRequest 2020-01-20 10:09:27 -08:00
Shu xian
8e1ff80b9e Merge pull request #1 from micro/master
merge
2020-01-20 20:08:21 +08:00
shu xian
94bb0f4c08 watch supports path 2020-01-20 18:31:18 +08:00
Allenxuxu
dbe209ebe4 Merge branch 'master' of https://github.com/micro/go-micro 2020-01-20 08:37:34 +08:00
Asim Aslam
fa0d884cfe fix bad import 2020-01-19 23:31:09 +00:00
Asim Aslam
ed2bd68d28 fix break in router service 2020-01-19 23:22:41 +00:00
Asim Aslam
97928e88f8 stop watcher 2020-01-19 23:15:57 +00:00
Asim Aslam
04cf86070c close stream 2020-01-19 22:55:57 +00:00
Asim Aslam
9df19e826e cancel stream 2020-01-19 22:53:56 +00:00
Asim Aslam
3f3c1919f4 strip certain plugins 2020-01-19 17:56:59 +00:00
Asim Aslam
d918694346 reorganise runtime 2020-01-19 17:47:27 +00:00
Asim Aslam
54fb61bba4 Move proto to service/ 2020-01-19 17:31:24 +00:00
Asim Aslam
fac75866d9 Move pool to util 2020-01-19 17:30:49 +00:00
Asim Aslam
a47ff65529 remove mock client 2020-01-19 17:24:22 +00:00
Asim Aslam
093bcedfe7 remove http broker 2020-01-19 17:21:55 +00:00
Asim Aslam
7b6d560bec Update README.md 2020-01-19 13:55:23 +00:00
Asim Aslam
43aa4e23bd update readme 2020-01-19 13:51:31 +00:00
Asim Aslam
bdd9ec560b strip sub comments 2020-01-19 13:47:14 +00:00
Asim Aslam
0c03bf064b only connect broker if there are subscribers 2020-01-19 13:45:28 +00:00
Asim Aslam
9a8c1b7ab8 update broker 2020-01-19 13:35:23 +00:00
Asim Aslam
e1ca40c1fc go fmt 2020-01-19 13:32:30 +00:00
Asim Aslam
e75b99f89c go fmt 2020-01-19 13:32:24 +00:00
Allenxuxu
ee7304a795 NewConfig return value error 2020-01-19 16:42:05 +08:00
Allenxuxu
a82fd19209 handle Loader.Load return value error 2020-01-19 16:31:02 +08:00
Asim Aslam
1983d607f3 set nats-e 2020-01-19 01:47:30 +00:00
Asim Aslam
10093a0ea2 set to nats-e 2020-01-19 01:29:00 +00:00
Asim Aslam
fc08a9146c Add broker comments on server subscribe 2020-01-19 01:16:36 +00:00
Asim Aslam
cafd280718 Default to grpc in registry service for now 2020-01-19 01:13:14 +00:00
Asim Aslam
11b104677a Shift embedded nats to the default 2020-01-19 00:55:01 +00:00
Asim Aslam
105596a0e5 use mucp server 2020-01-18 20:48:08 +00:00
Asim Aslam
0a37767127 Fix service registration with registry service 2020-01-18 19:53:51 +00:00
Asim Aslam
31e195bac7 strip image pull policy always 2020-01-18 18:37:38 +00:00
Asim Aslam
bdf1d20f4e extract an ip that can be advertised in embedded nats 2020-01-18 15:39:26 +00:00
shu xian
8d6f82707a update to standard name convention 2020-01-18 23:16:23 +08:00
Asim Aslam
058fd8adbf trace 1 2020-01-18 10:20:46 +00:00
Asim Aslam
13d1d2fa08 hard stop if graceful stop fails after 1 second 2020-01-18 10:18:23 +00:00
Asim Aslam
e666d0b807 add missing commit 2020-01-18 02:28:44 +00:00
Asim Aslam
39d7938405 Extract k8s run error 2020-01-18 02:13:24 +00:00
Asim Aslam
65df711b01 move nats local logic 2020-01-18 01:29:53 +00:00
Asim Aslam
fd6eb23307 do not wait to stop 2020-01-18 00:58:27 +00:00
Asim Aslam
fb3927fb8c Merge pull request #1126 from milosgajdos83/metric-update
Update route metric when receiving Sync routes
2020-01-17 18:29:55 +00:00
Milos Gajdos
891af703be Update route metric when receiving Sync routes 2020-01-17 18:24:36 +00:00
Asim Aslam
474472eedd Merge pull request #1124 from milosgajdos83/flush-advert-query
Use the same logic for advertising routes in Router and Network
2020-01-17 16:49:11 +00:00
Milos Gajdos
23d65145e6 Use the same logic for advertising routes in Router and Network
router.Query() allows to query the routes with given router.Strategy.
It uses the same logic as was implemented in flushRoutes but the code
was never updated. This way we are consistent across both router and
network packages.
2020-01-17 16:25:18 +00:00
shu xian
9ea4919b9b rename mucp source directory to service 2020-01-17 23:53:33 +08:00
Asim Aslam
f78e30770e Merge pull request #1123 from milosgajdos83/sync-metric
Update route metric before sending the Sync message
2020-01-17 15:44:49 +00:00
Milos Gajdos
bf9f319cdf Update route metric before sending the Sync message 2020-01-17 15:38:28 +00:00
shu xian
ad28b72dd3 rename mucpSource to service 2020-01-17 23:27:41 +08:00
Asim Aslam
8425ae77f8 Merge pull request #1122 from micro/blocking
don't block forever
2020-01-17 15:24:03 +00:00
Asim Aslam
d7b9b2713b don't block forever 2020-01-17 15:23:10 +00:00
Asim Aslam
be788415ad minor runtime fixes 2020-01-17 14:14:47 +00:00
shu xian
a03791c581 set DefaultClient 2020-01-17 21:32:00 +08:00
Asim Aslam
ee922a3da6 Merge pull request #1121 from milosgajdos83/no-routes-found
Continue processing Sync if no routes were returned from router Query
2020-01-17 13:05:47 +00:00
Milos Gajdos
624f1c1980 Continue processing Sync if no routes were returned from router Query 2020-01-17 12:58:13 +00:00
Milos Gajdos
607a226e34 Updated debug logs to make them less verbose 2020-01-17 12:14:56 +00:00
Asim Aslam
bac1bbfd97 Merge pull request #1120 from milosgajdos83/remove-solicit
Remove Solicitation from the network
2020-01-16 20:02:05 +00:00
Milos Gajdos
7f9b3b5556 Remove Solicitation from the network
Instead, when a new peer is discovered it is sent a sync message i.e. we
do the full sync when discovering peers
2020-01-16 19:43:10 +00:00
Asim Aslam
ba12513199 Merge pull request #1119 from milosgajdos83/sync-best-routes-only
Send only best routes via Sync. Only apply best routes.
2020-01-16 18:17:26 +00:00
Milos Gajdos
8fcfbc0d20 Strip unnecessary continue statement 2020-01-16 17:33:53 +00:00
Milos Gajdos
472186c1be Code consistency. Small bug fix. 2020-01-16 17:04:04 +00:00
Milos Gajdos
60c05bd899 Find the best routes in the routes we would advertise based on Strategy 2020-01-16 16:53:39 +00:00
Milos Gajdos
793e6013e5 Advertise routes with configured strategy. Simplify Sync apply logic 2020-01-16 16:42:23 +00:00
shu xian
071ab7aede add mucp for config/source 2020-01-17 00:10:15 +08:00
Milos Gajdos
eda8b00f84 Send only best routes via Sync. Only apply best routes. 2020-01-16 16:08:49 +00:00
Asim Aslam
eac2ab3c28 Merge pull request #1117 from micro/scheduler
Switch notifier to scheduler
2020-01-16 13:41:13 +00:00
Asim Aslam
76fba34c2f Merge pull request #1116 from milosgajdos83/query-strategy
QueryStrategy to allow querying routes based on Advertising Strategy
2020-01-16 13:39:39 +00:00
Asim Aslam
491a42d352 Switch notifier to scheduler 2020-01-16 13:34:04 +00:00
Milos Gajdos
5e85194a13 QueryStrategy to allow querying routes based on Advertising Strategy 2020-01-16 12:48:36 +00:00
Asim Aslam
689ae7cfc7 Storing tunnel.Session rather than transport.Client 2020-01-16 00:28:58 +00:00
Asim Aslam
19dbd77402 fix net masking in listed routes 2020-01-16 00:12:38 +00:00
Asim Aslam
b194b3adc9 Merge pull request #1115 from micro/net-mask
mask the route before sending
2020-01-15 23:13:53 +00:00
Asim Aslam
33a9b3bc17 mask the route before sending 2020-01-15 23:06:58 +00:00
Asim Aslam
6562154573 Fix the next panic 2020-01-15 21:38:37 +00:00
Asim Aslam
b32ebddf85 update nlopes/slack dep 2020-01-15 21:22:07 +00:00
Asim Aslam
b3e3dac975 Merge branch 'master' of ssh://github.com/micro/go-micro 2020-01-15 21:02:58 +00:00
Asim Aslam
f20e4daa60 fix rand panic 2020-01-15 21:02:53 +00:00
Asim Aslam
f67d87e99d Merge pull request #1114 from milosgajdos83/network-backward-compatibility
Fixed bug:m network.proto backwards compatibility unmarshal
2020-01-15 19:57:57 +00:00
Milos Gajdos
36928b716c Fixed bug:m network.proto backwards compatibility unmarshal 2020-01-15 19:45:43 +00:00
Asim Aslam
7c7b0ced5f Merge pull request #1104 from milosgajdos83/network-hackery
[WIP] Network hackery
2020-01-14 20:28:32 +00:00
Milos Gajdos
c67ef7e017 Bug fix: skip sending sync message if the peer is not in our graph 2020-01-14 19:37:50 +00:00
Milos Gajdos
dcd925f1e5 Code cleanup; Indentation. 2020-01-14 18:48:42 +00:00
Milos Gajdos
0ea56a5ffe Fixed tests 2020-01-14 18:22:58 +00:00
Milos Gajdos
821fda41ae Added Status method to network.Node fixed random segfaults. 2020-01-14 18:12:36 +00:00
Asim Aslam
1d311ab457 Embedded NATS Broker (#1110)
* if the address is produced by a default route don't hash it

* embedded nats

* fix url parsing

* don't override help

* add ready flag
2020-01-14 13:23:16 +00:00
Asim Aslam
b699d969e4 if the address is produced by a default route don't hash it (#1108) 2020-01-14 11:20:13 +00:00
Milos Gajdos
994d371ff1 Removed redundant comments. Add proper PruneStalePeers test. 2020-01-14 10:49:34 +00:00
Milos Gajdos
a91dad04ee Increment node error count and prune when Max limit is hit 2020-01-13 22:22:12 +00:00
Milos Gajdos
b4261e8cf9 Updated log and comments 2020-01-13 20:14:30 +00:00
Milos Gajdos
efcac3d009 Define tunnel errors 2020-01-13 20:14:30 +00:00
Milos Gajdos
770c7686ba Fix nasty bug when graph action may not have been executed in some
branches
2020-01-13 20:14:30 +00:00
Milos Gajdos
11904e1137 Regular sync with network every 5 minutes. Apply routes before peering. 2020-01-13 20:14:29 +00:00
Milos Gajdos
1e009e52dd Avoid having the same log statements in initNodes and resolveNodes 2020-01-13 20:14:29 +00:00
Milos Gajdos
bf42c028fb Added sync message. Refactored connect flow. Adverts are gossipped.
This commit adds a Sync message which is sent as a reply to Connect
message. This should in theory speed up convergence of a (re)connecting
node.

We respond to Sync message by sending a peer message back to the peer
origin of the Sync message. We consequently update our routing table and
peer graph with the data sent in via Sync message.

We now gossip advertse to up to 3 randomly selected peers instead of
sending a multicast message to the network.

Equally, Solicitation i.e. full table adverts are gossipped to a
randomly selected peer. If that fails we send a multicast message to the
network.
2020-01-13 20:14:29 +00:00
Milos Gajdos
0a4bd02503 Add RefreshSync method for Sync bookkeeping 2020-01-13 20:14:29 +00:00
Milos Gajdos
63edfaa852 Added Sync message
Sync message will be sent between peers when a new node connects/joins
the network
2020-01-13 20:14:29 +00:00
Milos Gajdos
802cc8239a Send solicit message properly. Updated comments. 2020-01-13 20:14:29 +00:00
Matthew Costa
75b1a62af3 Replace service prefix with FQDN style prefix (#1107)
* Replace service prefix with FQDN style prefix

According to the k8s documentation, the label and annotation prefixes should be in the format of a FQDN, with dot separated labels of no more than 63 characters. The current label and annotation paramteres are rejected by the k8s api, most likely because they have two forward slashes in them.

* Use go.micro as service and annotation prefix
2020-01-12 14:37:12 +00:00
Maarten Bezemer
50b20413d3 RPC stream client/server mutex fix (#884)
* Unlock RPC client while actually receiving a message

As receiving a message might block for a long time, unblocking the client allows to let it send messages in the meanwhile without using 'tricks'

* Unlock RPC server while actually receiving a message

As receiving a message might block for a long time, unblocking the client allows to let it send messages in the meanwhile without using 'tricks'

* Protect Close() against race conditions

* Concurrency and Sequence tests
2020-01-12 09:13:14 +00:00
Shu xian
fa5b3ee9d9 config/reader.Values add Set for specific path merge (#1099)
* add Set for specific path merge

* add Set

* add Del
2020-01-11 20:50:09 +00:00
Asim Aslam
f50a50eeb3 go fmt 2020-01-10 21:54:36 +00:00
Asim Aslam
e1e6199743 normalise runtime service status 2020-01-10 21:54:28 +00:00
Asim Aslam
61dd2b8489 Merge branch 'master' of ssh://github.com/micro/go-micro 2020-01-10 19:13:59 +00:00
Asim Aslam
6ca298c61d set default store, fix store options bug, add String method 2020-01-10 19:13:55 +00:00
f4fb923fb2 pass additional context for broker subscribe (#1105)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-01-10 15:04:15 +00:00
shikbupt
32a2005f6d add option for web service signal handler (#1091) 2020-01-10 14:25:28 +00:00
Asim Aslam
37d1139a57 ensure we close the grpc stream (#1098)
* ensure we close the grpc stream

* use g.Close

* use closed bool flag for checking connection close
2020-01-09 17:00:14 +00:00
Asim Aslam
a90a74c9e2 Change the store interface to remove variadic args (#1095) 2020-01-08 22:23:14 +00:00
Milos Gajdos
78aed5beed Fixed tunnel race conditions. (#1094) 2020-01-08 14:48:38 +00:00
Milos Gajdos
59fccb82ec Updated comments. Tiny cleanup changes. (#1093) 2020-01-08 13:18:11 +00:00
Asim Aslam
048065fe96 support ability to set store, address and namespace via flags and env vars (#1092) 2020-01-08 12:11:31 +00:00
Asim Aslam
0b8ff3a8bb fix grpc json streaming by setting content sub type (#1089) 2020-01-07 18:37:34 +00:00
Asim Aslam
1892bd05a5 only add api endpoint metadata if it exists (#1087) 2020-01-06 22:22:36 +00:00
Asim Aslam
be6e8a7c78 add store to defaults (#1086) 2020-01-06 17:44:32 +00:00
Asim Aslam
df9055f69c continue to process messages even after the connection is closed 2020-01-03 20:43:53 +00:00
Asim Aslam
649dd235c3 Merge branch 'master' of ssh://github.com/micro/go-micro 2020-01-03 19:46:24 +00:00
Asim Aslam
1af82df8b1 Check link is grpc 2020-01-03 19:46:14 +00:00
Eagle Wu
7098e59b5c remove ignore error in method publish (#1075) 2020-01-03 17:24:19 +00:00
Shu xian
31362bc331 prevent resource leak (#1080) 2020-01-03 13:31:47 +00:00
Asim Aslam
4e2339749c Merge branch 'master' of ssh://github.com/micro/go-micro 2020-01-02 21:19:50 +00:00
Asim Aslam
9cecf2e097 make grpc proxy streaming work 2020-01-02 21:11:25 +00:00
Lars Lehtonen
fe9c68238f runtime/kubernetes: remove unused name variable (#1078) 2020-01-02 20:42:46 +00:00
Asim Aslam
225b17559b fix log streaming 2020-01-02 18:23:43 +00:00
Asim Aslam
e697912ee5 don't panic on nil 2020-01-01 21:56:29 +00:00
Asim Aslam
6358b9277d don't write anything if theres no data 2019-12-31 22:58:14 +00:00
Asim Aslam
45c986c5f1 don't marshal frame values 2019-12-31 21:36:22 +00:00
Asim Aslam
fa01ff6604 update ctx test 2019-12-31 13:53:48 +00:00
Asim Aslam
fe1e018e8e update wrapper test 2019-12-31 13:45:49 +00:00
Asim Aslam
60ea537bbc upper case the metadata 2019-12-31 13:37:29 +00:00
Asim Aslam
488dc31743 log when starting the service 2019-12-31 12:07:52 +00:00
Asim Aslam
b6915f0898 set grpc by default (#1070) 2019-12-30 18:33:21 +00:00
Asim Aslam
04dfe4e867 fix breaking test 2019-12-30 17:39:02 +00:00
Asim Aslam
d8fe030a4b go fmt 2019-12-30 17:29:57 +00:00
Asim Aslam
f40d4578d5 go fmt 2019-12-30 17:29:45 +00:00
Asim Aslam
e0078bbcd5 Remove use of config/cmd in api 2019-12-30 17:29:20 +00:00
Asim Aslam
c145f355dd Moving to gRPC by default (#1069)
* Step 1

* Fix the test panics
2019-12-29 21:07:55 +00:00
943445270f fix registry check issue (#1067)
fix #1066

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2019-12-28 11:11:46 +00:00
Asim Aslam
61cde4a9f4 Kubernetes Registry (#1064)
* add teh k8s registry

* add k8s reg config/cmd

* go mod update
2019-12-27 20:08:46 +00:00
jamsonzan
22aa7d14b3 support streams pool for grpc (#1062)
* Update grpc_pool.go

* Update options.go

* Update grpc.go

* Update grpc_pool_test.go

* streams pool for grpc

* use busy list to speed up allocate while pool is very busy

* fix idle bug
2019-12-27 12:25:58 +00:00
Eagle Wu
a09b6729cc Fix missing recover while occur panic in handler (#1063) 2019-12-27 10:53:11 +00:00
Asim Aslam
2fe64001c0 Start runtime services inline 2019-12-24 17:51:30 +00:00
Asim Aslam
14c9c412cd Move and rename 2019-12-24 17:45:17 +00:00
Asim Aslam
361fdfba04 move around k8s api 2019-12-24 17:42:22 +00:00
Asim Aslam
5c8d1ae2b9 Update k8s log options 2019-12-24 17:33:05 +00:00
Asim Aslam
81e20160f5 reorder 2019-12-23 08:49:53 +00:00
Asim Aslam
ef95b28e3d add Write method to config source 2019-12-23 08:42:57 +00:00
shikbupt
1781542964 fix etcd LogConfig bug (#1056) 2019-12-23 07:29:13 +00:00
Asim Aslam
45208992b5 NewLog 2019-12-20 23:36:16 +00:00
Asim Aslam
847a01df82 Cleanup k8s logs 2019-12-20 23:34:08 +00:00
Jake Sanders
ce33e3b072 Kubernetes logging (#1054)
* wip

* Implementation of Kubernetes Logger

* Missing file

* Skip test in Travis
2019-12-20 23:16:05 +00:00
Asim Aslam
ae12fd1021 update crap logging 2019-12-19 18:25:22 +00:00
Asim Aslam
95ae2688a2 add formatters 2019-12-19 12:29:03 +00:00
Asim Aslam
2bcfb85613 Add log Format option 2019-12-19 12:20:33 +00:00
Asim Aslam
d52a111735 add requests/errors to stats 2019-12-18 18:36:42 +00:00
Asim Aslam
d4bec24eb7 Add os log buffer 2019-12-18 17:06:29 +00:00
Asim Aslam
2338e7c9d2 Cleanup go mod 2019-12-18 16:12:25 +00:00
Asim Aslam
f0e841595c move to structured logging 2019-12-18 16:02:11 +00:00
Asim Aslam
a82af19d43 strip newline 2019-12-18 15:19:20 +00:00
Asim Aslam
5d7254e79a fix the os logger 2019-12-18 15:06:25 +00:00
Asim Aslam
7c21a1b92a go fmt 2019-12-18 15:06:02 +00:00
Asim Aslam
587f64a87a Merge pull request #1051 from micro/event
publisher => event
2019-12-18 15:04:38 +00:00
Asim Aslam
cb9c4c3aef publisher => event 2019-12-17 23:05:46 +00:00
Asim Aslam
dda96cb87e Merge pull request #976 from micro/auth
First interface for auth
2019-12-17 21:38:11 +00:00
Asim Aslam
ebae497a72 use service rather than resource 2019-12-17 21:37:20 +00:00
Asim Aslam
515014fbeb update with resource 2019-12-17 21:27:05 +00:00
Asim Aslam
e9efcbe8dc strip logger 2019-12-17 18:34:21 +00:00
Asim Aslam
5a52593e66 go fmt 2019-12-17 18:24:00 +00:00
Asim Aslam
c61e12d5ee add event proto for runtiem 2019-12-17 18:17:32 +00:00
Asim Aslam
c2d59c1f4d Move logger 2019-12-17 18:16:45 +00:00
Jake Sanders
812fe9e640 Merge pull request #1049 from micro/kubernetes-logging
Kubernetes logging
2019-12-17 17:44:24 +00:00
Jake Sanders
f95bccce84 Use UTC in tests 2019-12-17 17:36:01 +00:00
Jake Sanders
81e7edd666 Adhere to new interfaces 2019-12-17 17:24:01 +00:00
Asim Aslam
46fd205eda rename files 2019-12-17 17:08:38 +00:00
Jake Sanders
c2b307e5bb Merge branch master of https://github.com/micro/go-micro into kubernetes-logging 2019-12-17 17:08:31 +00:00
Jake Sanders
b7ac62f7d2 Merge branch 'master' of https://github.com/micro/go-micro into kubernetes-logging 2019-12-17 17:06:07 +00:00
Asim Aslam
50d5c6402b Merge pull request #1048 from micro/logging
Move stream to interface
2019-12-17 17:05:13 +00:00
Asim Aslam
d2a3fd0b04 Move stream to interface 2019-12-17 16:56:55 +00:00
Jake Sanders
51f4bc6d56 Add logs to Interface 2019-12-17 16:30:09 +00:00
Jake Sanders
c3607c23e7 Fix after merge 2019-12-17 16:27:17 +00:00
Jake Sanders
34b1c403bb Merge branch 'master' of https://github.com/micro/go-micro into kubernetes-logging 2019-12-17 16:13:36 +00:00
Asim Aslam
91e057440d Merge pull request #1047 from micro/decruft-logger
Decruft logger
2019-12-17 16:13:20 +00:00
Jake Sanders
53ca742c66 Update the util/kubernetes client to retrieve logs 2019-12-17 16:09:51 +00:00
Asim Aslam
b35dfb1086 fix further breaks 2019-12-17 15:56:49 +00:00
Asim Aslam
d502e2f58a fix breaks 2019-12-17 15:46:09 +00:00
Asim Aslam
bc30efcf70 Decruft the debug logger interface 2019-12-17 15:38:03 +00:00
Jake Sanders
0415ead504 First commit for Kubernetes logger 2019-12-17 12:11:26 +00:00
Jake Sanders
e95f44d3f8 Move runtime/kubernetes/client to util/kubernetes/client 2019-12-17 11:32:38 +00:00
Asim Aslam
0489ae91e9 Merge pull request #1021 from unistack-org/registry_check
add RegisterCheck web server option for internal health checks
2019-12-17 08:49:00 +00:00
Asim Aslam
4e02f444fd Merge pull request #1024 from unistack-org/server
add server Context option to pass own context
2019-12-17 08:48:39 +00:00
Asim Aslam
6027a81f06 Update router comments 2019-12-17 08:28:45 +00:00
Asim Aslam
01f0e70213 add some commented out stuff 2019-12-16 17:37:11 +00:00
Asim Aslam
cb15fadcee go fmt 2019-12-16 17:36:47 +00:00
Asim Aslam
1c8d15fe4b Merge pull request #1046 from micro/storefix
Fix cockroachdb store implementation
2019-12-16 17:24:53 +00:00
Jake Sanders
55f5937c8b Remove debug 2019-12-16 17:16:10 +00:00
Jake Sanders
56619f2745 Fix cockroachdb store implemetation 2019-12-16 17:11:13 +00:00
Asim Aslam
0b59e2ce3d Merge pull request #1028 from Astone-Chou/fix
named return value for error defer modify.
2019-12-16 15:39:58 +00:00
Asim Aslam
1ea6390eae Add proxy string method 2019-12-16 15:18:20 +00:00
Asim Aslam
303adca500 rename postgres to cockroach 2019-12-16 15:09:59 +00:00
Asim Aslam
03700ae6c0 Replace proxy options 2019-12-16 14:55:47 +00:00
Asim Aslam
a1ddfa827e Merge pull request #1045 from micro/store-options
change store options
2019-12-16 14:46:15 +00:00
Asim Aslam
59751c02e6 change store options 2019-12-16 14:38:51 +00:00
Jake Sanders
e8e112144f Create database should take the name of the database 2019-12-16 14:15:30 +00:00
Asim Aslam
59246e0412 Merge pull request #1044 from micro/store-namespace
change use of store namespace/prefix in sql store
2019-12-16 12:20:57 +00:00
Asim Aslam
0131e9468f change use of store namespace/prefix in sql store 2019-12-16 12:13:18 +00:00
Asim Aslam
d5951f1d7c Merge pull request #1042 from ZGeomantic/feat-client-mock
support ctx as input params, error as output for MockClient.Call
2019-12-15 15:12:17 +00:00
Asim Aslam
f33b562c16 Merge pull request #1043 from jamsonzan/branch0
comment
2019-12-15 10:50:52 +00:00
jamsonzan
572fe58314 comment 2019-12-15 15:05:19 +08:00
gemantic
5602b93d7a support ctx as input params, error as output for MockClient.Call 2019-12-14 10:36:12 +08:00
Asim Aslam
64e438a8d4 Merge pull request #1038 from micro/tun
Next level tunnel optimisation
2019-12-13 15:34:03 +00:00
Asim Aslam
b0b6b8fce2 final updates 2019-12-13 15:27:47 +00:00
Asim Aslam
417a05db60 Merge pull request #1039 from xpunch/etcdLogConfig
Etcd log config
2019-12-13 09:23:54 +00:00
johnson
11e42aac69 etcd can set log config
default log level is info, which will log o log of unused logs
2019-12-13 11:22:05 +08:00
potato
885ba8f905 Merge pull request #6 from micro/master
Pull latest go-micro
2019-12-13 11:10:29 +08:00
Asim Aslam
caa74d1b5f fix build 2019-12-12 23:29:44 +00:00
Asim Aslam
f6b4a9da1c strip some code 2019-12-12 23:20:31 +00:00
Asim Aslam
74c5102e41 strip a couple things 2019-12-12 21:49:39 +00:00
Asim Aslam
7bd50cd251 fix more broken cruft 2019-12-12 17:10:32 +00:00
Asim Aslam
df728aaddd remove go routines from tunnel, fire network messages in go routines 2019-12-12 13:34:08 +00:00
Asim Aslam
ae934c19f1 fix tunnel test 2019-12-12 13:04:34 +00:00
Asim Aslam
e260cc4a24 save cruft 2019-12-12 12:27:46 +00:00
Asim Aslam
631faff7b8 Merge pull request #1035 from alrs/fix-grpc-test-goroutines
Fix service/grpc Test Goroutines
2019-12-11 16:39:22 +00:00
Lars Lehtonen
fd531349d7 service/grpc: t.Fatal out of TestGRPCTLSService() goroutine 2019-12-11 08:29:23 -08:00
Lars Lehtonen
27bab29e3c service/grpc: t.Fatal out of TestGRPCService() goroutine 2019-12-11 08:29:14 -08:00
Asim Aslam
27af221fd2 batch metric updates 2019-12-11 15:23:08 +00:00
Asim Aslam
6e28e7a86f Save current state of the world 2019-12-11 14:37:03 +00:00
Asim Aslam
ff69d46c98 strip some cruft from config/cmd 2019-12-10 18:12:29 +00:00
Asim Aslam
e966944ae5 sort resolved node list in network by lowest priority 2019-12-10 17:57:04 +00:00
Asim Aslam
8da77a3ddc use fixed port names for runtime k8s 2019-12-10 14:05:05 +00:00
Asim Aslam
8289dbabc4 Merge pull request #1034 from micro/strip-handlers
Strip handlers
2019-12-10 11:54:06 +00:00
Asim Aslam
d50f30d743 strip handlers 2019-12-10 11:46:13 +00:00
Asim Aslam
f8533551a4 move debug to trace for network peer refresh 2019-12-10 09:09:24 +00:00
Asim Aslam
7e46ff5d92 strip some more logging down 2019-12-10 09:08:03 +00:00
Asim Aslam
6b1eef5354 Merge branch 'master' of ssh://github.com/micro/go-micro 2019-12-09 22:56:33 +00:00
Asim Aslam
b29da80539 Move a few things around 2019-12-09 22:56:26 +00:00
Asim Aslam
a725ab2c94 Merge pull request #1032 from jankremlacek/patch-1
nlopes/slack dep update to fix broken unmarshal
2019-12-09 21:17:34 +00:00
Jan Kremlacek
1582aa1572 proper go.mod, go.sum 2019-12-09 22:08:57 +01:00
Jan Kremlacek
5352d53346 nlopes/slack dep update to fix broken unmarshal
About a month ago Slack introduced the updated structure of RTM messages which resulted in an inability to unmarshal received msg (original issue: https://github.com/nlopes/slack/issues/630). It's not an issue of micro itself, but of the github.com/nlopes/slack lib. The fix was already merged into master (https://github.com/nlopes/slack/pull/618), but the lib has not been released in any new version.

Thus so I propose to update directly to the commit:

go get github.com/nlopes/slack@d06c2a2b3249b44a9c5dee8485f5a87497beb9ea

The MicroBot does now work now with any Slack client newer than around a month old.
2019-12-09 21:52:28 +01:00
Asim Aslam
7d884eff9d Merge pull request #1031 from alrs/fix-web-test-goroutines
web: fix test goroutines
2019-12-09 18:03:07 +00:00
Lars Lehtonen
c9af88184b web: fix test goroutine in TestService() 2019-12-09 09:44:14 -08:00
Lars Lehtonen
f25ad35f0a web: fix test goroutine in TestTLS() 2019-12-09 09:28:42 -08:00
Asim Aslam
55ab44c8be Merge branch 'master' of ssh://github.com/micro/go-micro 2019-12-09 09:32:33 +00:00
Asim Aslam
59c1680594 Move Debug to Trace in router 2019-12-09 09:32:17 +00:00
Asim Aslam
b804303aa0 Merge pull request #1029 from Astone-Chou/lint_fix_fix
fix tiny error in linting fixes
2019-12-09 07:47:46 +00:00
Astone
55a15ecf12 fix tiny error in linting fixes 2019-12-09 11:18:45 +08:00
Astone
caa1bcf9fe named return value for error defer modify. 2019-12-09 11:08:21 +08:00
Asim Aslam
e2b2a30668 add net/http/pprof profiler 2019-12-08 20:31:16 +00:00
Asim Aslam
a9be1288d2 Merge pull request #1026 from micro/tun
Network & Tunnel refactor
2019-12-08 16:01:46 +00:00
Asim Aslam
679214e598 just return filtered routes 2019-12-08 15:39:45 +00:00
Asim Aslam
6064e1426c fix some potential go routine leaks 2019-12-08 15:02:54 +00:00
Asim Aslam
d28a868e46 Fix network startup connect 2019-12-08 14:37:17 +00:00
Asim Aslam
398acc67ca fix broken test 2019-12-08 13:45:24 +00:00
Asim Aslam
ce578800d0 n.initNodes 2019-12-08 12:17:31 +00:00
Asim Aslam
6307d6ba51 further cleanup of tunnel/network 2019-12-08 12:12:20 +00:00
Asim Aslam
283c85d256 done 2019-12-08 00:53:55 +00:00
Asim Aslam
9bd0fb9125 save changes 2019-12-07 23:28:39 +00:00
Asim Aslam
c445aed6b1 Cleanup and speedup network convergence along with direct messaging for connect and solicit 2019-12-07 19:54:29 +00:00
Asim Aslam
1d8c66780e save working solution 2019-12-06 00:18:40 +00:00
Asim Aslam
219efd27e9 Optimise the multicast to use one session in the tunnel 2019-12-05 23:11:42 +00:00
Asim Aslam
ac9001ac74 advert ttl inline with router table tick 2019-12-05 17:50:32 +00:00
Asim Aslam
2896614595 Merge pull request #1025 from milosgajdos83/router-knobs
Changed a few router knobs to avoid storms ⛈
2019-12-05 17:50:02 +00:00
Milos Gajdos
bca12a7003 Changed a few router knobs to avoid storms ⛈ 2019-12-05 17:11:17 +00:00
1c5a4c470f add server Context option to pass own context
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2019-12-05 19:37:03 +03:00
Asim Aslam
744b19d625 Merge pull request #1023 from milosgajdos83/dead-code
Fixing dead code and go vet moaning
2019-12-05 16:18:13 +00:00
Milos Gajdos
5865e89bed Fixing dead code and go vet moaning 2019-12-05 16:10:49 +00:00
Asim Aslam
3a10b1cdde Merge pull request #1022 from milosgajdos83/tunnel-races
This PR fixes various tunnel race conditions
2019-12-05 15:59:29 +00:00
Milos Gajdos
5db7514a91 This PR fixes various tunnel race conditions 2019-12-05 15:50:32 +00:00
a957e90ca8 add RegisterCheck web server option for internal health checks
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2019-12-05 17:28:11 +03:00
Asim Aslam
18cf025056 Merge pull request #1020 from Allenxuxu/master
Avoid excessive memory usage
2019-12-05 11:56:44 +00:00
Allenxuxu
b55b7d6b20 replace map with list 2019-12-05 19:29:48 +08:00
Asim Aslam
26b5d1994a Merge pull request #1019 from tboerger/no-newlin
No newlines at end of log messages
2019-12-05 10:08:16 +00:00
Thomas Boerger
30aec5b872 No newlines at end of log messages
Log messages should not end with a new line, this should be entirely
handled by the underlying log library.

Signed-off-by: Thomas Boerger <thomas@webhippie.de>
2019-12-05 10:56:45 +01:00
Asim Aslam
b0626089f3 Merge pull request #1016 from unistack-org/lint
lint fixes mostly for prealloc also remove deadcode from grpc client
2019-12-05 08:33:52 +00:00
Asim Aslam
af3d4e595f in memory stats buffer 2019-12-05 00:08:46 +00:00
Asim Aslam
40c09eed1c Logs to Log 2019-12-05 00:01:17 +00:00
Asim Aslam
fe46e7a9e9 Logs to Log 2019-12-04 23:58:29 +00:00
Asim Aslam
78647c7027 add timestamp to stats 2019-12-04 23:51:07 +00:00
Asim Aslam
26755f86b1 Merge pull request #1018 from micro/debug-service
Debug service
2019-12-04 14:40:58 +00:00
Asim Aslam
898848795b tab indent 2019-12-04 12:28:16 +00:00
Asim Aslam
24efbe6a41 Move debug handler to service dir 2019-12-04 12:27:30 +00:00
Asim Aslam
97433f716f add service name to debug proto 2019-12-04 12:02:44 +00:00
Asim Aslam
5200febaea add stats debug interface 2019-12-04 11:53:20 +00:00
a1eaf9cc20 linting fixes
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2019-12-04 00:22:02 +03:00
Asim Aslam
3f8af8c1e0 Merge branch 'master' of ssh://github.com/micro/go-micro 2019-12-03 20:32:10 +00:00
Asim Aslam
becaeefcba Revert. DO NOT peer solicit until we know better 2019-12-03 20:32:02 +00:00
7d5bdcf993 fix pointer dereference in memory registry
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2019-12-03 23:05:03 +03:00
Asim Aslam
81a7cf458c Merge pull request #1013 from unistack-org/linting
add golanglint-ci
2019-12-03 16:57:00 +00:00
Asim Aslam
a4ea61334b Merge pull request #1015 from milosgajdos83/router-race
Fix router race condition
2019-12-03 16:55:56 +00:00
Asim Aslam
3fbba9f83d Merge pull request #1014 from milosgajdos83/memreg-race
Fix memory registry race
2019-12-03 16:51:36 +00:00
Milos Gajdos
4a11a4c546 Fix router race condition 2019-12-03 15:22:54 +00:00
Milos Gajdos
265233517e Fix memory registry race 2019-12-03 14:53:07 +00:00
c581ceb1dc add golanglint-ci
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2019-12-03 16:31:43 +03:00
Asim Aslam
bb1a1358b7 Merge pull request #1012 from Astone-Chou/lint
improve code quality
2019-12-03 13:10:04 +00:00
Astone
29fb58db39 improve code quality 2019-12-03 20:59:02 +08:00
Asim Aslam
b6f0164501 Merge branch 'master' of ssh://github.com/micro/go-micro 2019-12-03 08:11:46 +00:00
Asim Aslam
2c0801fc1c couple bug fixes in tunnel 2019-12-03 08:11:36 +00:00
Asim Aslam
34c92f4964 Merge pull request #1011 from Astone-Chou/master
optimize: a better way for return error
2019-12-03 07:48:21 +00:00
Astone
f9b900b2ca optimize: a better way for return error 2019-12-03 12:47:29 +08:00
Asim Aslam
b5d65305db Merge pull request #1009 from unistack-org/panics
recover panics
2019-12-02 23:30:17 +00:00
b8e96f45d4 add recovery in case of panics
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2019-12-03 02:25:40 +03:00
90f9b0d0c9 initialize client options context if not provided
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2019-12-03 01:35:59 +03:00
Asim Aslam
972c0989af Merge pull request #1008 from micro/connect-fast
Optimizations to connect fast
2019-12-02 19:09:56 +00:00
Asim Aslam
5f04fd58ab optimizations to connect fast 2019-12-02 18:48:19 +00:00
Asim Aslam
da04aa8ae8 Switch to AdvertiseLocal by default 2019-12-02 17:36:20 +00:00
Asim Aslam
62bf0df864 Merge pull request #1007 from micro/ultra-hacks
ultra hacks to make debug handler work in proxy
2019-12-02 15:11:56 +00:00
Asim Aslam
91e9c0cb62 ultra hacks to make debug handler work in proxy 2019-12-02 14:55:35 +00:00
Asim Aslam
3356b83f24 register debug handler 2019-12-01 21:04:09 +00:00
Asim Aslam
795ec509fd Merge branch 'master' of ssh://github.com/micro/go-micro 2019-12-01 19:43:45 +00:00
Asim Aslam
93d66afe8c fix that broken logic 2019-12-01 19:43:36 +00:00
Asim Aslam
c840cee404 A variety of fixes to try combat the multicast issue 2019-12-01 19:36:16 +00:00
Milos Gajdos
e48cce6485 Merge pull request #1005 from milosgajdos83/nano-seconds
Time resolution change to be in line with debug/handler.Handler
2019-12-01 18:39:59 +00:00
Milos Gajdos
b2ecd93404 Time resolution change to be in line with debug/handler.Handler 2019-12-01 18:33:08 +00:00
Asim Aslam
2928c66624 Merge pull request #1004 from milosgajdos83/debug-logs
[WIP] Debug logs
2019-12-01 17:40:40 +00:00
Milos Gajdos
4613a820ca Small refactoring og logs
* log.Write now accepts log.Record
* we stream last 10 records first
* regenerate proto because of the above
2019-12-01 13:16:44 +00:00
Milos Gajdos
ecdadef633 Added hack support for logs streaming cruft 2019-12-01 13:16:44 +00:00
Milos Gajdos
7f1dea72f2 Simplified Logs RPC. Cleaned up code. Added comments. 2019-12-01 13:16:44 +00:00
Milos Gajdos
612f872f76 Server should not close the stream when done 2019-12-01 13:16:44 +00:00
Milos Gajdos
13d2a9ec7a Register proto handler properly 2019-12-01 13:16:44 +00:00
Milos Gajdos
9fab47ecdb Added DefaultLog variables 2019-12-01 13:16:44 +00:00
Milos Gajdos
265e8ade05 Embed DebugHandler proto 2019-12-01 13:16:44 +00:00
Milos Gajdos
60e0e81523 Added debug/service to grab the logs from a service 2019-12-01 13:16:43 +00:00
Milos Gajdos
b01357058a Regenerate proto cruft 2019-12-01 13:16:43 +00:00
Milos Gajdos
7deafbc5ce Added ReadOptions; Changed proto; Reimplemented Log(er) 2019-12-01 13:16:43 +00:00
Milos Gajdos
9e177be560 Embed logger into debug.Handler 2019-12-01 13:16:43 +00:00
Milos Gajdos
ee9776e7b2 Added debug.Logger interface 2019-12-01 13:16:43 +00:00
Milos Gajdos
3f7f2afc7b Dont be stupid -- stream does not require pointer. 2019-12-01 13:16:43 +00:00
Milos Gajdos
4e965e4ce5 First commit. Modified proto. Added empty handler method. 2019-12-01 13:16:43 +00:00
Asim Aslam
6f1c30aef5 remove unused value in router 2019-11-30 21:39:03 +00:00
Asim Aslam
00bbb3ac61 revert some protocol changes for now 2019-11-30 21:20:33 +00:00
Asim Aslam
ce1942c578 why didn't we think of this before...single service name for http broker 2019-11-30 21:00:36 +00:00
Asim Aslam
df7169c9f2 Merge branch 'master' of ssh://github.com/micro/go-micro 2019-11-30 01:16:53 +00:00
Asim Aslam
5e59db4c6d revert mdns timeout 2019-11-30 01:16:32 +00:00
Asim Aslam
25b3fda25b Merge pull request #1002 from micro/tun-fix
fix bug in the tunnel which causes multicast connections to be closed
2019-11-30 01:16:12 +00:00
Asim Aslam
9678daeafa fix bug in the tunnel which causes multicast connections to be closed 2019-11-30 01:14:40 +00:00
Asim Aslam
9ed257f151 Merge pull request #1001 from micro/storm
Changes for the storm
2019-11-29 17:33:23 +00:00
Asim Aslam
107124e5dc Changes for the storm 2019-11-29 17:27:29 +00:00
Asim Aslam
ce4acfa892 fix type filtering for k8s runtime 2019-11-29 13:05:18 +00:00
Asim Aslam
6bf4828296 triple the mdns timeout 2019-11-29 13:05:07 +00:00
Asim Aslam
76b4e78a6a fix command to accept variadic args 2019-11-29 11:55:25 +00:00
Asim Aslam
8b6475b8d4 Merge pull request #1000 from micro/runtime-type
Support service types in runtime
2019-11-29 11:46:21 +00:00
Asim Aslam
c3ed83dfba Support service types in runtime 2019-11-29 11:35:00 +00:00
Asim Aslam
114bc1e18b Merge pull request #995 from micro/rpc-leak
Fix rpc go routine leak
2019-11-27 17:24:19 +00:00
Asim Aslam
af94899b54 Fix rpc go routine leak 2019-11-27 17:12:07 +00:00
Asim Aslam
266b6dbc64 add debug buffer time based access 2019-11-27 13:57:19 +00:00
Asim Aslam
5932dd753c Merge pull request #981 from unistack-org/subscriber
subscriber recovery
2019-11-27 10:28:51 +00:00
86a6328254 subscriber recovery
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2019-11-27 13:21:20 +03:00
Asim Aslam
0d33c029a9 Merge pull request #994 from milosgajdos83/validator-regexp
Remove validator regexp as its no longer needed.
2019-11-27 08:10:00 +00:00
Milos Gajdos
8ecd2381a4 Remove validator regexp as its no longer needed. 2019-11-26 23:10:45 +00:00
Asim Aslam
7318807dce Merge pull request #993 from micro/k8s-fixes
Add fixes for label selector and skipping things that don't match
2019-11-26 22:32:58 +00:00
Asim Aslam
811275be26 Add fixes for label selector and skipping things that don't match 2019-11-26 22:28:08 +00:00
Asim Aslam
3f3fd38601 Add spec.template.metadata.annotations to the k8s template 2019-11-26 18:14:49 +00:00
Asim Aslam
44dd0b1302 Merge pull request #991 from micro/k8s-update
Patch spec template annotations and use event timestmap
2019-11-26 17:38:56 +00:00
Asim Aslam
6475c1f3ad Patch spec template annotations and use event timestmap 2019-11-26 17:33:41 +00:00
Asim Aslam
deabf0b8c9 fix entry into nil map 2019-11-26 14:56:23 +00:00
Asim Aslam
04ee4b04ad Merge pull request #990 from micro/buffer
Add debug/buffer package as a simple ring buffer
2019-11-26 14:27:39 +00:00
Asim Aslam
2892686c5f Merge pull request #988 from micro/k8s-update
Change the k8s runtime notifier update to get the deployment and upda…
2019-11-26 14:21:42 +00:00
Asim Aslam
8ee31a63f1 Add debug/buffer package as a simple ring buffer 2019-11-26 14:20:45 +00:00
Asim Aslam
4e363da91f Merge pull request #989 from micro/proto
Regenerate the protos
2019-11-26 13:57:49 +00:00
Asim Aslam
8b63df7a98 regenerate the protos 2019-11-26 13:53:33 +00:00
Asim Aslam
b06854b0d5 Change the k8s runtime notifier update to get the deployment and update build 2019-11-26 13:49:52 +00:00
Jake Sanders
39bf71376a Add some more issue templates (#987)
* Add some more issue templates

* Update bug_report.md

* Update bug_report.md
2019-11-26 11:48:14 +00:00
Jake Sanders
12d9c5b187 Merge pull request #986 from micro/bug-report-template
Create Bug Report Issue Template
2019-11-26 11:25:42 +00:00
Jake Sanders
d2eba3f8f9 Create Bug Report Issue Template
To encourage users to provide context with bug reports
2019-11-26 11:17:32 +00:00
Milos Gajdos
19f2f8b161 Merge pull request #982 from xmlking/master
go-micro docker now includes unprivileged user
2019-11-26 10:54:18 +00:00
Sumanth Chinthagunta
d41185eb84 go-micro docker now includes unprivileged user 2019-11-25 18:42:24 -08:00
Asim Aslam
c420fa2dec Merge pull request #979 from milosgajdos83/tunnel-encrypt
[WIP] Tunnel encryption
2019-11-25 19:12:24 +00:00
Asim Aslam
db03a564fb Merge pull request #980 from unistack-org/issue-940
grpc client goroutine leak fix
2019-11-25 19:10:34 +00:00
9763820c75 grpc client goroutine leak fix
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2019-11-25 22:02:24 +03:00
Milos Gajdos
9095b99f6b Token has been stripped; Headers are encrypted 2019-11-25 18:56:00 +00:00
Asim Aslam
080363e8c4 The mega cruft proxy PR (#974)
* the mega cruft proxy PR

* Rename broker id

* add protocol=grpc

* fix compilation breaks

* Add the tunnel broker to the network

* fix broker id

* continue to be backwards compatible in the protocol
2019-11-25 16:31:43 +00:00
Asim Aslam
252667398e Update the runtime for k8s name formatting and move Get to Read endpoint (#978)
* Update the runtime for k8s name formatting and move Get to Read endpoint

* strip regex validation
2019-11-25 16:31:14 +00:00
Milos Gajdos
f82c267d81 Encrypt session communication 2019-11-25 15:37:38 +00:00
Milos Gajdos
61fe552ac4 First commit: Outline of tunnel encryption code 2019-11-25 14:58:12 +00:00
Asim Aslam
7013e7467f Undefined time 2019-11-25 09:33:30 +00:00
Asim Aslam
dbc537007d First interface for auth 2019-11-25 09:30:26 +00:00
Asim Aslam
95045be83d Merge branch 'master' of ssh://github.com/micro/go-micro 2019-11-23 22:50:45 +00:00
Asim Aslam
52ccd900c7 reorder service struct fields 2019-11-23 22:50:13 +00:00
罗泽轩
64a251d69a improve the syncMap.Iterate test to make it 100% reproducible (#970)
* improve the syncMap.Iterate test to make it 100% reproducible

* rename store/mocks/Store.go

* rename mocks/store to mock/store
2019-11-23 14:13:17 +00:00
Asim Aslam
cae4148594 Fix platform specific os/process build 2019-11-23 08:25:56 +00:00
Milos Gajdos
38e29c5101 Svc metadata (#972)
* Added service metadata

* Added metadata to runtime service

* Add Annotations metadata to service metadata

* Add micro/micro as default service owners

* Update runtime/kubernetes/client/kubernetes.go

Change comment

Co-Authored-By: Jake Sanders <i@am.so-aweso.me>
2019-11-22 17:10:00 +00:00
Milos Gajdos
8dc3fb964e Pass source of service to Deployment API; render templates properly (#969)
* Pass source of service to Deployment API; render templates properly

* Enable Go modules by default. Honor runtime.Service.Exec

* Make sure you remove go.mod and go.sum
2019-11-21 17:31:13 +00:00
Asim Aslam
212144d658 fix windows compilation error 2019-11-21 11:19:52 +00:00
Milos Gajdos
11d81221cc Runtime service implementation (#965) 2019-11-20 14:54:42 +00:00
Milos Gajdos
55252cbc32 Fix the router test; get rid of time dependency (#964) 2019-11-20 14:53:12 +00:00
Asim Aslam
c87a58db0a add ability to set web icon 2019-11-20 12:43:43 +00:00
49d73faa5f return error to caller on grpc server request processing (#962)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2019-11-20 10:28:30 +00:00
da6c1be607 dont panic on missing headers in broker event (#963)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2019-11-20 07:55:47 +00:00
Milos Gajdos
94d409b180 Change DefaultImage to micro/go-micro 2019-11-19 20:49:01 +00:00
Milos Gajdos
d6e97c5970 Service.Exec is a slice of strings (#960) 2019-11-19 19:36:29 +00:00
Asim Aslam
64d5a528ca fix broken build 2019-11-19 16:55:33 +00:00
Milos Gajdos
538d3752f9 Added Dockerfile for go-micro (#959) 2019-11-19 16:50:31 +00:00
Asim Aslam
fb5b358ae2 fix mdns test 2019-11-19 16:50:16 +00:00
Milos Gajdos
6a0082741c Packager is now builder (#958) 2019-11-19 16:09:43 +00:00
Shu xian
5744050943 api event supports for GET url params (#956) 2019-11-18 16:37:45 +00:00
Asim Aslam
168cc06827 increase timeout on travis 2019-11-18 12:58:06 +00:00
Asim Aslam
fa01cadc35 lower the mdns timeout to 10ms (#955) 2019-11-18 12:50:51 +00:00
Asim Aslam
342c29de7d fix TestMemoryRegistryTTLConcurrent test 2019-11-16 21:13:06 +00:00
Asim Aslam
eeed493766 move test data 2019-11-16 18:52:27 +00:00
Asim Aslam
90d7a87914 Move wrapper internally since its not top level relevant 2019-11-16 18:48:24 +00:00
Erik Hollensbe
a1c6cdf193 Now specify HandleSignal as an option to toggle signal handling. (#948)
Signed-off-by: Erik Hollensbe <github@hollensbe.org>
2019-11-16 11:13:34 +00:00
Erik Hollensbe
bec13a45cd Attempt to fix the timing error in the memory concurrency test (#952)
Only shows in travis

Signed-off-by: Erik Hollensbe <github@hollensbe.org>
2019-11-16 11:11:13 +00:00
Erik Hollensbe
4107733453 Memory registry from #801 with additional tweaks (#951)
* PoC: memory registry using maps instead of slice madness

* Updated proto and handlers. Fixed tests across codebase.

* Implemented ttl pruning for memory registry

* Added extensive memory registry tests

* Squased a bunch of bugs

* Proto indent; memory.Registry.String() returns "memory"

* Write a test to prove memory registry TTLs are busted

Signed-off-by: Erik Hollensbe <github@hollensbe.org>

* Additional memory testing and fixups:

* DefaultTTL removed
* When TTL == 0, it is automatically removed from expiry conditions
* Additional improvements to new tests

Signed-off-by: Erik Hollensbe <github@hollensbe.org>
2019-11-16 10:55:11 +00:00
Milos Gajdos
97c1300f53 [WIP] Micro Runtime (#947)
* Add Get() and GetOptions.

* Removed watcher. Outline of client. YAML templates

* Added default service and deployment templates and types

* Added API tests and cleaned up errors.

* Small refactoring. Template package is no more.

* Ripped out existing code in preparation to small rework

* Reshuffled the source code to make it organized better

* Create service and deployment in kubernetes runtime

* Major cleanup and refactoring of Kubernetes runtime

* Service now handles low level K8s API calls across both K8s deployment
an service API objects
* Runtime has a task queue that serves for queueing runtime action
requests
* General refactoring

* No need for Lock in k8s service

* Added kubernetes runtime env var to default deployment

* Enable running different versions of the same service

* Can't delete services through labels

* Proto cruft. Added runtime.CreateOptions implementation in proto

* Removed proxy service from default env variables

* Make service name mandatory param to Get method

* Get Delete changes from https://github.com/micro/go-micro/pull/945

* Replaced template files with global variables

* Validate service names before sending K8s API request

* Refactored Kubernetes API client. Fixed typos.

* Added client.Resource to make API resources more explicit in code
2019-11-15 13:41:40 +00:00
mirwaisx
0af8be35bb -bugfix #889 set body corretly in case of missing content-type (#950) 2019-11-15 13:03:45 +00:00
Asim Aslam
a91b3f3e8b windows specific os tag 2019-11-15 08:20:05 +00:00
Asim Aslam
383658edf2 Fix a runtime deadlock as well as fixing some graceful exiting issues (#945) 2019-11-14 14:26:21 +00:00
Asim Aslam
16754a7477 Set theme jekyll-theme-architect 2019-11-14 11:55:07 +00:00
Asim Aslam
58b25d7241 Update CNAME 2019-11-14 11:54:16 +00:00
Asim Aslam
1c7d44282e Set theme jekyll-theme-minimal 2019-11-14 11:17:02 +00:00
Asim Aslam
8e9eef794f Set theme jekyll-theme-minimal 2019-11-14 11:15:50 +00:00
Asim Aslam
920c026f14 Create CNAME 2019-11-14 11:01:36 +00:00
Asim Aslam
946c76cb03 Delete CNAME 2019-11-14 11:01:27 +00:00
Asim Aslam
43d11a9b8d Create CNAME 2019-11-14 10:50:51 +00:00
Asim Aslam
9f481542f3 Fix a codec race by locking the buffers. Include a buffer pool for perf. (#941)
* Fix a codec race by locking the buffers. Include a buffer pool for perf.

* Read Lock on buffer Read
2019-11-13 11:05:53 +00:00
Asim Aslam
cffa5b6b50 Make use of cloudflare 1.0.0.1 by default to resolve addresses 2019-11-12 15:46:30 +00:00
Asim Aslam
8867539d78 Update FUNDING.yml 2019-11-12 12:35:09 +00:00
Asim Aslam
671408b3a5 Create FUNDING.yml 2019-11-12 12:27:51 +00:00
Lars Lehtonen
bdb62e8ed1 store/postgresql: fix dropped error (#938) 2019-11-12 07:54:33 +00:00
Asim Aslam
72522a869a fix endpoint extractor panic 2019-11-11 17:37:48 +00:00
Asim Aslam
fd5c29addc Add the ability to only advertise local routes or don't advertise at all (#932)
* Add the ability to only advertise local routes or don't advertise at all

* Reorder processing to shortcircuit no advertising
2019-11-11 15:28:37 +00:00
Asim Aslam
65b1283459 add metadata.Get(context, key) as short hand 2019-11-11 09:13:02 +00:00
Huang.X
5ffe367cae fix# Change the Log level and add WarnLevel (#935)
* fix# Change the Log level and add WarnLevel

* fix# Change the Log level and add WarnLevel
2019-11-11 07:57:13 +00:00
Till Knuesting
5ae3e179b9 preallocated slices (#934) 2019-11-11 00:03:51 +00:00
c696a859be fix data race for server Wait option (#931)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2019-11-09 21:52:41 +00:00
Asim Aslam
174b01ca29 update link in readme 2019-11-09 16:20:54 +00:00
Asim Aslam
c433de80cd Update go mod 2019-11-09 15:44:52 +00:00
Asim Aslam
f2b4c07a00 Merge branch 'master' of ssh://github.com/micro/go-micro 2019-11-09 15:37:54 +00:00
Asim Aslam
929ffdcc42 Update readme 2019-11-09 15:37:30 +00:00
Lars Lehtonen
5aa28dfb0d store/cloudflare: fix dropped error (#930) 2019-11-09 15:18:51 +00:00
Asim Aslam
a9e8fc6039 Don't set stream unless its true 2019-11-09 10:32:52 +00:00
Milos Gajdos
0b1e6d7eaf Simplified k8s API Body watcher code and test. (#923) 2019-11-08 15:57:32 +00:00
Milos Gajdos
1ffa289d39 Make build timestamp parsing errors clearer (#929) 2019-11-08 15:57:07 +00:00
Milos Gajdos
68419cc024 Patch deployment spec metadata (#928) 2019-11-08 14:12:03 +00:00
8227206208 use service id in profile file name (#925)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2019-11-08 09:11:55 +00:00
Milos Gajdos
6f28852e1b K8s list deployments (#921)
* Outline of ListDeployments method

* Added implementation of DeploymentList
2019-11-07 07:44:57 +00:00
Asim Aslam
0e3550229b update readme 2019-11-06 22:04:02 +00:00
Asim Aslam
f9400ba713 update readme 2019-11-06 22:03:35 +00:00
Asim Aslam
ce080d76c6 add debug/profile package (#920)
* add debug/profile package

* set service+version for profile
2019-11-06 19:36:04 +00:00
Asim Aslam
254045e9f3 Remove go routines for mdns watcher and cache registry (#919) 2019-11-06 15:49:40 +00:00
Milos Gajdos
b84134581c Flap detection vol2 (#915)
* We now purge flapping routes before regular tick processes them

* Updated comments

* Record the timestamp as soon as you receive the event

* Set route Address to routing table test

* Fixed a bunch of deadlocks. Added basic Router tests.
2019-11-05 17:44:24 +00:00
Till Knuesting
f67c5e779f preallocated slices (#917) 2019-11-05 17:43:12 +00:00
Milos Gajdos
4a694c9d02 Change flap detection configuration (#914)
* Change flap detection configuration

* Make PenaltyHalfLife a float, not int 🤦‍♂️

* Lower event suppression to 200
2019-11-04 19:01:52 +00:00
Till Knuesting
24b8d2a315 preallocating slices (#904)
* preallocated some slices when size is known

* gofmt

* gofmt
2019-11-04 10:33:53 +00:00
Asim Aslam
2f3c251b00 Recovery should be < 500 2019-11-03 17:10:00 +00:00
potato
f933457cc1 Merge pull request #5 from micro/master
pull request from go-micro
2019-09-30 17:22:51 +08:00
627 changed files with 18497 additions and 55166 deletions

24
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@@ -0,0 +1,24 @@
---
name: Bug report
about: For reporting bugs in go-micro
title: "[BUG]"
labels: ''
assignees: ''
---
**Describe the bug**
1. What are you trying to do?
2. What did you expect to happen?
3. What happens instead?
**How to reproduce the bug:**
If possible, please include a minimal code snippet here.
**Environment:**
Go Version: please paste `go version` output here
```
please paste `go env` output here
```

View File

@@ -0,0 +1,17 @@
---
name: Feature request / Enhancement
about: If you have a need not served by go-micro
title: "[FEATURE]"
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Additional context**
Add any other context or screenshots about the feature request here.

14
.github/ISSUE_TEMPLATE/question.md vendored Normal file
View File

@@ -0,0 +1,14 @@
---
name: Question
about: Ask a question about go-micro
title: ''
labels: ''
assignees: ''
---
Before asking, please check if your question has already been answered:
1. Check the documentation - https://micro.mu/docs/
2. Check the examples and plugins - https://github.com/micro/examples & https://github.com/micro/go-plugins
3. Search existing issues

9
.github/PULL_REQUEST_TEMPLATE.md vendored Normal file
View File

@@ -0,0 +1,9 @@
## Pull Request template
Please, go through these steps before clicking submit on this PR.
1. Give a descriptive title to your PR.
2. Provide a description of your changes.
3. Make sure you have some relevant tests.
4. Put `closes #XXXX` in your comment to auto-close the issue that your PR fixes (if applicable).
**PLEASE REMOVE THIS TEMPLATE BEFORE SUBMITTING**

15
.github/generate.sh vendored Executable file
View File

@@ -0,0 +1,15 @@
#!/bin/bash -e
find . -type f -name '*.pb.*.go' -o -name '*.pb.go' -a ! -name 'message.pb.go' -delete
PROTOS=$(find . -type f -name '*.proto' | grep -v proto/google/api)
mkdir -p proto/google/api
curl -s -o proto/google/api/annotations.proto -L https://raw.githubusercontent.com/googleapis/googleapis/master/google/api/annotations.proto
curl -s -o proto/google/api/http.proto -L https://raw.githubusercontent.com/googleapis/googleapis/master/google/api/http.proto
for PROTO in $PROTOS; do
echo $PROTO
protoc -I./proto -I. -I$(dirname $PROTO) --go-grpc_out=paths=source_relative:. --go_out=paths=source_relative:. --micro_out=paths=source_relative:. $PROTO
done
rm -r proto

20
.github/renovate.json vendored Normal file
View File

@@ -0,0 +1,20 @@
{
"extends": [
"config:base"
],
"postUpdateOptions": ["gomodTidy"],
"packageRules": [
{
"matchUpdateTypes": ["minor", "patch", "pin", "digest"],
"automerge": true
},
{
"groupName": "all deps",
"separateMajorMinor": true,
"groupSlug": "all",
"packagePatterns": [
"*"
]
}
]
}

13
.github/stale.sh vendored Executable file
View File

@@ -0,0 +1,13 @@
#!/bin/bash -ex
export PATH=$PATH:$(pwd)/bin
export GO111MODULE=on
export GOBIN=$(pwd)/bin
#go get github.com/rvflash/goup@v0.4.1
#goup -v ./...
#go get github.com/psampaz/go-mod-outdated@v0.6.0
go list -u -m -mod=mod -json all | go-mod-outdated -update -direct -ci || true
#go list -u -m -json all | go-mod-outdated -update

62
.github/workflows/build.yml vendored Normal file
View File

@@ -0,0 +1,62 @@
name: build
on:
push:
branches:
- master
jobs:
test:
name: test
runs-on: ubuntu-latest
steps:
- name: setup
uses: actions/setup-go@v2
with:
go-version: 1.16
- name: cache
uses: actions/cache@v2
with:
path: ~/go/pkg/mod
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
restore-keys: ${{ runner.os }}-go-
- name: sdk checkout
uses: actions/checkout@v2
- name: sdk deps
run: go get -v -t -d ./...
- name: sdk test
env:
INTEGRATION_TESTS: yes
run: go test -mod readonly -v ./...
- name: tests checkout
uses: actions/checkout@v2
with:
repository: unistack-org/micro-tests
ref: refs/heads/master
path: micro-tests
fetch-depth: 1
- name: tests deps
run: |
cd micro-tests
go mod edit -replace="github.com/unistack-org/micro/v3=../"
go get -v -t -d ./...
- name: tests test
env:
INTEGRATION_TESTS: yes
run: cd micro-tests && go test -mod readonly -v ./...
lint:
name: lint
runs-on: ubuntu-latest
steps:
- name: checkout
uses: actions/checkout@v2
- name: lint
uses: golangci/golangci-lint-action@v2
continue-on-error: true
with:
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
version: v1.30
# Optional: working directory, useful for monorepos
# working-directory: somedir
# Optional: golangci-lint command line arguments.
# args: --issues-exit-code=0
# Optional: show only new issues if it's a pull request. The default value is `false`.
# only-new-issues: true

62
.github/workflows/pr.yml vendored Normal file
View File

@@ -0,0 +1,62 @@
name: prbuild
on:
pull_request:
branches:
- master
jobs:
test:
name: test
runs-on: ubuntu-latest
steps:
- name: setup
uses: actions/setup-go@v2
with:
go-version: 1.16
- name: cache
uses: actions/cache@v2
with:
path: ~/go/pkg
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
restore-keys: ${{ runner.os }}-go-
- name: sdk checkout
uses: actions/checkout@v2
- name: sdk deps
run: go get -v -t -d ./...
- name: sdk test
env:
INTEGRATION_TESTS: yes
run: go test -mod readonly -v ./...
- name: tests checkout
uses: actions/checkout@v2
with:
repository: unistack-org/micro-tests
ref: refs/heads/master
path: micro-tests
fetch-depth: 1
- name: tests deps
run: |
cd micro-tests
go mod edit -replace="github.com/unistack-org/micro/v3=../"
go get -v -t -d ./...
- name: tests test
env:
INTEGRATION_TESTS: yes
run: cd micro-tests && go test -mod readonly -v ./...
lint:
name: lint
runs-on: ubuntu-latest
steps:
- name: checkout
uses: actions/checkout@v2
- name: lint
uses: golangci/golangci-lint-action@v2
continue-on-error: true
with:
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
version: v1.30
# Optional: working directory, useful for monorepos
# working-directory: somedir
# Optional: golangci-lint command line arguments.
# args: --issues-exit-code=0
# Optional: show only new issues if it's a pull request. The default value is `false`.
# only-new-issues: true

30
.golangci.yml Normal file
View File

@@ -0,0 +1,30 @@
run:
deadline: 5m
modules-download-mode: readonly
skip-files:
- ".*\\.pb\\.go$"
- ".*\\.pb\\.micro\\.go$"
linters:
disable-all: false
enable-all: false
enable:
- megacheck
- staticcheck
- deadcode
- varcheck
- gosimple
- unused
- prealloc
- scopelint
- gocritic
- goimports
- unconvert
- govet
- nakedret
- structcheck
- gosec
disable:
- maligned
- interfacer
- typecheck
- dupl

View File

@@ -1,11 +0,0 @@
language: go
go:
- 1.13.x
env:
- GO111MODULE=on IN_TRAVIS_CI=yes
notifications:
slack:
secure: aEvhLbhujaGaKSrOokiG3//PaVHTIrc3fBpoRbCRqfZpyq6WREoapJJhF+tIpWWOwaC9GmChbD6aHo/jMUgwKXVyPSaNjiEL87YzUUpL8B2zslNp1rgfTg/LrzthOx3Q1TYwpaAl3to0fuHUVFX4yMeC2vuThq7WSXgMMxFCtbc=
cache:
directories:
- $GOPATH/pkg/mod

View File

@@ -176,7 +176,8 @@
END OF TERMS AND CONDITIONS
Copyright 2015 Asim Aslam.
Copyright 2015-2020 Asim Aslam.
Copyright 2019-2020 Unistack LLC.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.

View File

@@ -1,27 +1,27 @@
# Go Micro [![License](https://img.shields.io/:license-apache-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![GoDoc](https://godoc.org/github.com/micro/go-micro?status.svg)](https://godoc.org/github.com/micro/go-micro) [![Travis CI](https://api.travis-ci.org/micro/go-micro.svg?branch=master)](https://travis-ci.org/micro/go-micro) [![Go Report Card](https://goreportcard.com/badge/micro/go-micro)](https://goreportcard.com/report/github.com/micro/go-micro)
# Micro [![License](https://img.shields.io/:license-apache-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![Doc](https://img.shields.io/badge/go.dev-reference-007d9c?logo=go&logoColor=white&style=flat-square)](https://pkg.go.dev/github.com/unistack-org/micro/v3?tab=overview) [![Status](https://github.com/unistack-org/micro/workflows/build/badge.svg?branch=master)](https://github.com/unistack-org/micro/actions?query=workflow%3Abuild+branch%3Amaster+event%3Apush) [![Lint](https://goreportcard.com/badge/github.com/unistack-org/micro)](https://goreportcard.com/report/github.com/unistack-org/micro) [![Slack](https://img.shields.io/static/v1?label=micro&message=slack&color=blueviolet)](https://unistack-org.slack.com/messages/default)
Go Micro is a framework for microservice development.
Micro is a standard library for microservices.
## Overview
Go Micro provides the core requirements for distributed systems development including RPC and Event driven communication.
The **micro** philosophy is sane defaults with a pluggable architecture. We provide defaults to get you started quickly
but everything can be easily swapped out.
<img src="https://micro.mu/docs/images/go-micro.svg" />
Plugins are available at [github.com/micro/go-plugins](https://github.com/micro/go-plugins).
Follow us on [Twitter](https://twitter.com/microhq) or join the [Slack](http://slack.micro.mu/) community.
Micro provides the core requirements for distributed systems development including RPC and Event driven communication.
## Features
Go Micro abstracts away the details of distributed systems. Here are the main features.
Micro abstracts away the details of distributed systems. Here are the main features.
- **Authentication** - Auth is built in as a first class citizen. Authentication and authorization enable secure
zero trust networking by providing every service an identity and certificates. This additionally includes rule
based access control.
- **Dynamic Config** - Load and hot reload dynamic config from anywhere. The config interface provides a way to load application
level config from any source such as env vars, file, etcd. You can merge the sources and even define fallbacks.
- **Data Storage** - A simple data store interface to read, write and delete records. It includes support for memory, file and
CockroachDB by default. State and persistence becomes a core requirement beyond prototyping and Micro looks to build that into the framework.
- **Service Discovery** - Automatic service registration and name resolution. Service discovery is at the core of micro service
development. When service A needs to speak to service B it needs the location of that service. The default discovery mechanism is
multicast DNS (mdns), a zeroconf system. You can optionally set gossip using the SWIM protocol for p2p networks or consul for a
resilient cloud-native setup.
development. When service A needs to speak to service B it needs the location of that service.
- **Load Balancing** - Client side load balancing built on service discovery. Once we have the addresses of any number of instances
of a service we now need a way to decide which node to route to. We use random hashed load balancing to provide even distribution
@@ -29,21 +29,24 @@ across the services and retry a different node if there's a problem.
- **Message Encoding** - Dynamic message encoding based on content-type. The client and server will use codecs along with content-type
to seamlessly encode and decode Go types for you. Any variety of messages could be encoded and sent from different clients. The client
and server handle this by default. This includes protobuf and json by default.
and server handle this by default.
- **Request/Response** - RPC based request/response with support for bidirectional streaming. We provide an abstraction for synchronous
communication. A request made to a service will be automatically resolved, load balanced, dialled and streamed. The default
transport is http/1.1 or http2 when tls is enabled.
- **Transport** - gRPC or http based request/response with support for bidirectional streaming. We provide an abstraction for synchronous communication. A request made to a service will be automatically resolved, load balanced, dialled and streamed.
- **Async Messaging** - PubSub is built in as a first class citizen for asynchronous communication and event driven architectures.
Event notifications are a core pattern in micro service development. The default messaging is point-to-point http/1.1 or http2 when tls
is enabled.
- **Async Messaging** - PubSub is built in as a first class citizen for asynchronous communication and event driven architectures.
Event notifications are a core pattern in micro service development.
- **Pluggable Interfaces** - Go Micro makes use of Go interfaces for each distributed system abstraction. Because of this these interfaces
are pluggable and allows Go Micro to be runtime agnostic. You can plugin any underlying technology. Find plugins in
[github.com/micro/go-plugins](https://github.com/micro/go-plugins).
- **Synchronization** - Distributed systems are often built in an eventually consistent manner. Support for distributed locking and
leadership are built in as a Sync interface. When using an eventually consistent database or scheduling use the Sync interface.
- **Pluggable Interfaces** - Micro makes use of Go interfaces for each system abstraction. Because of this these interfaces
are pluggable and allows Micro to be runtime agnostic.
## Getting Started
See the [docs](https://micro.mu/docs/go-micro.html) for detailed information on the architecture, installation and use of go-micro.
To be created.
## License
Micro is Apache 2.0 licensed.

View File

@@ -1,36 +0,0 @@
# Go Micro [![License](https://img.shields.io/:license-apache-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![GoDoc](https://godoc.org/github.com/micro/go-micro?status.svg)](https://godoc.org/github.com/micro/go-micro) [![Travis CI](https://api.travis-ci.org/micro/go-micro.svg?branch=master)](https://travis-ci.org/micro/go-micro) [![Go Report Card](https://goreportcard.com/badge/micro/go-micro)](https://goreportcard.com/report/github.com/micro/go-micro)
Go Micro是基于Golang的微服务开发框架。
## 概览
Go Micro提供分布式系统开发的核心库包含RPC与事件驱动的通信机制。
**micro**的设计哲学是可插拔的架构理念,她提供可快速构建系统的组件,并且可以根据自身的需求剥离默认实现并自行定制。
<img src="https://micro.mu/docs/images/go-micro.svg" />
所有插件可在仓库[github.com/micro/go-plugins](https://github.com/micro/go-plugins)中找到。
可以订阅我们的[Twitter](https://twitter.com/microhq)或者加入[Slack](http://slack.micro.mu/)论坛。
## 特性
Go Micro把分布式系统的各种细节抽象出来。下面是它的主要特性。
- **服务发现Service Discovery** - 自动服务注册与名称解析。服务发现是微服务开发中的核心。当服务A要与服务B协作时它得知道B在哪里。默认的服务发现系统是Consul而multicast DNS (mdns组播)机制作为本地解决方案或者零依赖的P2P网络中的SWIM协议gossip
- **负载均衡Load Balancing** - 在服务发现之上构建了负载均衡机制。当我们得到一个服务的任意多个的实例节点时,我们要一个机制去决定要路由到哪一个节点。我们使用随机处理过的哈希负载均衡机制来保证对服务请求颁发的均匀分布,并且在发生问题时进行重试。
- **消息编码Message Encoding** - 支持基于内容类型content-type动态编码消息。客户端和服务端会一起使用content-type的格式来对Go进行无缝编/解码。各种各样的消息被编码会发送到不同的客户端客户端服服务端默认会处理这些消息。content-type默认包含proto-rpc和json-rpc。
- **Request/Response** - RPC通信基于支持双向流的请求/响应方式我们提供有抽象的同步通信机制。请求发送到服务时会自动解析、负载均衡、拨号、转成字节流。默认的传输协议是http/1.1而tls下使用http2协议。
- **异步消息Async Messaging** - 发布订阅PubSub头等功能内置在异步通信与事件驱动架构中。事件通知在微服务开发中处于核心位置。默认的消息传送使用点到点http/1.1激活tls时则使用http2。
- **可插拔接口Pluggable Interfaces** - Go Micro为每个分布式系统抽象出接口。因此Go Micro的接口都是可插拔的允许其在运行时不可知的情况下仍可支持。所以只要实现接口可以在内部使用任何的技术。更多插件请参考[github.com/micro/go-plugins](https://github.com/micro/go-plugins)。
## 快速上手
更多关于架构、安装的资料可以查看[文档](https://micro.mu/docs/cn/)。

View File

@@ -1,2 +0,0 @@
// Package agent provides an interface for building robots
package agent

View File

@@ -1,54 +0,0 @@
// Package command is an interface for defining bot commands
package command
var (
// Commmands keyed by golang/regexp patterns
// regexp.Match(key, input) is used to match
Commands = map[string]Command{}
)
// Command is the interface for specific named
// commands executed via plugins or the bot.
type Command interface {
// Executes the command with args passed in
Exec(args ...string) ([]byte, error)
// Usage of the command
Usage() string
// Description of the command
Description() string
// Name of the command
String() string
}
type cmd struct {
name string
usage string
description string
exec func(args ...string) ([]byte, error)
}
func (c *cmd) Description() string {
return c.description
}
func (c *cmd) Exec(args ...string) ([]byte, error) {
return c.exec(args...)
}
func (c *cmd) Usage() string {
return c.usage
}
func (c *cmd) String() string {
return c.name
}
// NewCommand helps quickly create a new command
func NewCommand(name, usage, description string, exec func(args ...string) ([]byte, error)) Command {
return &cmd{
name: name,
usage: usage,
description: description,
exec: exec,
}
}

View File

@@ -1,65 +0,0 @@
package command
import (
"testing"
)
func TestCommand(t *testing.T) {
c := &cmd{
name: "test",
usage: "test usage",
description: "test description",
exec: func(args ...string) ([]byte, error) {
return []byte("test"), nil
},
}
if c.String() != c.name {
t.Fatalf("expected name %s got %s", c.name, c.String())
}
if c.Usage() != c.usage {
t.Fatalf("expected usage %s got %s", c.usage, c.Usage())
}
if c.Description() != c.description {
t.Fatalf("expected description %s got %s", c.description, c.Description())
}
if r, err := c.Exec(); err != nil {
t.Fatal(err)
} else if string(r) != "test" {
t.Fatalf("expected exec result test got %s", string(r))
}
}
func TestNewCommand(t *testing.T) {
c := &cmd{
name: "test",
usage: "test usage",
description: "test description",
exec: func(args ...string) ([]byte, error) {
return []byte("test"), nil
},
}
nc := NewCommand(c.name, c.usage, c.description, c.exec)
if nc.String() != c.name {
t.Fatalf("expected name %s got %s", c.name, nc.String())
}
if nc.Usage() != c.usage {
t.Fatalf("expected usage %s got %s", c.usage, nc.Usage())
}
if nc.Description() != c.description {
t.Fatalf("expected description %s got %s", c.description, nc.Description())
}
if r, err := nc.Exec(); err != nil {
t.Fatal(err)
} else if string(r) != "test" {
t.Fatalf("expected exec result test got %s", string(r))
}
}

View File

@@ -1,22 +0,0 @@
# Discord input for micro-bot
[Discord](https://discordapp.com) support for micro bot based on [discordgo](github.com/bwmarrin/discordgo).
This was originally written by Aleksandr Tihomirov (@zet4) and can be found at https://github.com/zet4/micro-misc/.
## Options
### discord_token
You have to supply an application token via `--discord_token`.
Head over to Discord's [developer introduction](https://discordapp.com/developers/docs/intro)
to learn how to create applications and how the API works.
### discord_prefix
Set a command prefix with `--discord_prefix`. The default prefix is `Micro `.
You can mention the bot or use the prefix to run a command.
### discord_whitelist
Pass a list of comma-separated user IDs with `--discord_whitelist`. Only allow
these users to use the bot.

View File

@@ -1,94 +0,0 @@
package discord
import (
"errors"
"strings"
"sync"
"github.com/bwmarrin/discordgo"
"github.com/micro/go-micro/agent/input"
"github.com/micro/go-micro/util/log"
)
type discordConn struct {
master *discordInput
exit chan struct{}
recv chan *discordgo.Message
sync.Mutex
}
func newConn(master *discordInput) *discordConn {
conn := &discordConn{
master: master,
exit: make(chan struct{}),
recv: make(chan *discordgo.Message),
}
conn.master.session.AddHandler(func(s *discordgo.Session, m *discordgo.MessageCreate) {
if m.Author.ID == master.botID {
return
}
whitelisted := false
for _, ID := range conn.master.whitelist {
if m.Author.ID == ID {
whitelisted = true
break
}
}
if len(master.whitelist) > 0 && !whitelisted {
return
}
var valid bool
m.Message.Content, valid = conn.master.prefixfn(m.Message.Content)
if !valid {
return
}
conn.recv <- m.Message
})
return conn
}
func (dc *discordConn) Recv(event *input.Event) error {
for {
select {
case <-dc.exit:
return errors.New("connection closed")
case msg := <-dc.recv:
event.From = msg.ChannelID + ":" + msg.Author.ID
event.To = dc.master.botID
event.Type = input.TextEvent
event.Data = []byte(msg.Content)
return nil
}
}
}
func (dc *discordConn) Send(e *input.Event) error {
fields := strings.Split(e.To, ":")
_, err := dc.master.session.ChannelMessageSend(fields[0], string(e.Data))
if err != nil {
log.Log("[bot][loop][send]", err)
}
return nil
}
func (dc *discordConn) Close() error {
if err := dc.master.session.Close(); err != nil {
return err
}
select {
case <-dc.exit:
return nil
default:
close(dc.exit)
}
return nil
}

View File

@@ -1,153 +0,0 @@
package discord
import (
"fmt"
"sync"
"errors"
"strings"
"github.com/bwmarrin/discordgo"
"github.com/micro/cli"
"github.com/micro/go-micro/agent/input"
)
func init() {
input.Inputs["discord"] = newInput()
}
func newInput() *discordInput {
return &discordInput{}
}
type discordInput struct {
token string
whitelist []string
prefix string
prefixfn func(string) (string, bool)
botID string
session *discordgo.Session
sync.Mutex
running bool
exit chan struct{}
}
func (d *discordInput) Flags() []cli.Flag {
return []cli.Flag{
cli.StringFlag{
Name: "discord_token",
EnvVar: "MICRO_DISCORD_TOKEN",
Usage: "Discord token (prefix with Bot if it's for bot account)",
},
cli.StringFlag{
Name: "discord_whitelist",
EnvVar: "MICRO_DISCORD_WHITELIST",
Usage: "Discord Whitelist (seperated by ,)",
},
cli.StringFlag{
Name: "discord_prefix",
Usage: "Discord Prefix",
EnvVar: "MICRO_DISCORD_PREFIX",
Value: "Micro ",
},
}
}
func (d *discordInput) Init(ctx *cli.Context) error {
token := ctx.String("discord_token")
whitelist := ctx.String("discord_whitelist")
prefix := ctx.String("discord_prefix")
if len(token) == 0 {
return errors.New("require token")
}
d.token = token
d.prefix = prefix
if len(whitelist) > 0 {
d.whitelist = strings.Split(whitelist, ",")
}
return nil
}
func (d *discordInput) Start() error {
if len(d.token) == 0 {
return errors.New("missing discord configuration")
}
d.Lock()
defer d.Unlock()
if d.running {
return nil
}
var err error
d.session, err = discordgo.New(d.token)
if err != nil {
return err
}
u, err := d.session.User("@me")
if err != nil {
return err
}
d.botID = u.ID
d.prefixfn = CheckPrefixFactory(fmt.Sprintf("<@%s> ", d.botID), fmt.Sprintf("<@!%s> ", d.botID), d.prefix)
d.exit = make(chan struct{})
d.running = true
return nil
}
func (d *discordInput) Stream() (input.Conn, error) {
d.Lock()
defer d.Unlock()
if !d.running {
return nil, errors.New("not running")
}
//Fire-n-forget close just in case...
d.session.Close()
conn := newConn(d)
if err := d.session.Open(); err != nil {
return nil, err
}
return conn, nil
}
func (d *discordInput) Stop() error {
d.Lock()
defer d.Unlock()
if !d.running {
return nil
}
close(d.exit)
d.running = false
return nil
}
func (d *discordInput) String() string {
return "discord"
}
// CheckPrefixFactory Creates a prefix checking function and stuff.
func CheckPrefixFactory(prefixes ...string) func(string) (string, bool) {
return func(content string) (string, bool) {
for _, prefix := range prefixes {
if strings.HasPrefix(content, prefix) {
return strings.TrimPrefix(content, prefix), true
}
}
return "", false
}
}

View File

@@ -1,55 +0,0 @@
// Package input is an interface for bot inputs
package input
import (
"github.com/micro/cli"
)
type EventType string
const (
TextEvent EventType = "text"
)
var (
// Inputs keyed by name
// Example slack or hipchat
Inputs = map[string]Input{}
)
// Event is the unit sent and received
type Event struct {
Type EventType
From string
To string
Data []byte
Meta map[string]interface{}
}
// Input is an interface for sources which
// provide a way to communicate with the bot.
// Slack, HipChat, XMPP, etc.
type Input interface {
// Provide cli flags
Flags() []cli.Flag
// Initialise input using cli context
Init(*cli.Context) error
// Stream events from the input
Stream() (Conn, error)
// Start the input
Start() error
// Stop the input
Stop() error
// name of the input
String() string
}
// Conn interface provides a way to
// send and receive events. Send and
// Recv both block until succeeding
// or failing.
type Conn interface {
Close() error
Recv(*Event) error
Send(*Event) error
}

View File

@@ -1,160 +0,0 @@
package slack
import (
"errors"
"fmt"
"strings"
"sync"
"time"
"github.com/micro/go-micro/agent/input"
"github.com/nlopes/slack"
)
// Satisfies the input.Conn interface
type slackConn struct {
auth *slack.AuthTestResponse
rtm *slack.RTM
exit chan bool
sync.Mutex
names map[string]string
}
func (s *slackConn) run() {
// func retrieves user names and maps to IDs
setNames := func() {
names := make(map[string]string)
users, err := s.rtm.Client.GetUsers()
if err != nil {
return
}
for _, user := range users {
names[user.ID] = user.Name
}
s.Lock()
s.names = names
s.Unlock()
}
setNames()
t := time.NewTicker(time.Minute)
defer t.Stop()
for {
select {
case <-s.exit:
return
case <-t.C:
setNames()
}
}
}
func (s *slackConn) getName(id string) string {
s.Lock()
name := s.names[id]
s.Unlock()
return name
}
func (s *slackConn) Close() error {
select {
case <-s.exit:
return nil
default:
close(s.exit)
}
return nil
}
func (s *slackConn) Recv(event *input.Event) error {
if event == nil {
return errors.New("event cannot be nil")
}
for {
select {
case <-s.exit:
return errors.New("connection closed")
case e := <-s.rtm.IncomingEvents:
switch ev := e.Data.(type) {
case *slack.MessageEvent:
// only accept type message
if ev.Type != "message" {
continue
}
// only accept DMs or messages to me
switch {
case strings.HasPrefix(ev.Channel, "D"):
case strings.HasPrefix(ev.Text, s.auth.User):
case strings.HasPrefix(ev.Text, fmt.Sprintf("<@%s>", s.auth.UserID)):
default:
continue
}
// Strip username from text
switch {
case strings.HasPrefix(ev.Text, s.auth.User):
args := strings.Split(ev.Text, " ")[1:]
ev.Text = strings.Join(args, " ")
event.To = s.auth.User
case strings.HasPrefix(ev.Text, fmt.Sprintf("<@%s>", s.auth.UserID)):
args := strings.Split(ev.Text, " ")[1:]
ev.Text = strings.Join(args, " ")
event.To = s.auth.UserID
}
if event.Meta == nil {
event.Meta = make(map[string]interface{})
}
// fill in the blanks
event.From = ev.Channel + ":" + ev.User
event.Type = input.TextEvent
event.Data = []byte(ev.Text)
event.Meta["reply"] = ev
return nil
case *slack.InvalidAuthEvent:
return errors.New("invalid credentials")
}
}
}
}
func (s *slackConn) Send(event *input.Event) error {
var channel, message, name string
if len(event.To) == 0 {
return errors.New("require Event.To")
}
parts := strings.Split(event.To, ":")
if len(parts) == 2 {
channel = parts[0]
name = s.getName(parts[1])
// try using reply meta
} else if ev, ok := event.Meta["reply"]; ok {
channel = ev.(*slack.MessageEvent).Channel
name = s.getName(ev.(*slack.MessageEvent).User)
}
// don't know where to send the message
if len(channel) == 0 {
return errors.New("could not determine who message is to")
}
if len(name) == 0 || strings.HasPrefix(channel, "D") {
message = string(event.Data)
} else {
message = fmt.Sprintf("@%s: %s", name, string(event.Data))
}
s.rtm.SendMessage(s.rtm.NewOutgoingMessage(message, channel))
return nil
}

View File

@@ -1,147 +0,0 @@
package slack
import (
"errors"
"sync"
"github.com/micro/cli"
"github.com/micro/go-micro/agent/input"
"github.com/nlopes/slack"
)
type slackInput struct {
debug bool
token string
sync.Mutex
running bool
exit chan bool
api *slack.Client
}
func init() {
input.Inputs["slack"] = NewInput()
}
func (p *slackInput) Flags() []cli.Flag {
return []cli.Flag{
cli.BoolFlag{
Name: "slack_debug",
Usage: "Slack debug output",
EnvVar: "MICRO_SLACK_DEBUG",
},
cli.StringFlag{
Name: "slack_token",
Usage: "Slack token",
EnvVar: "MICRO_SLACK_TOKEN",
},
}
}
func (p *slackInput) Init(ctx *cli.Context) error {
debug := ctx.Bool("slack_debug")
token := ctx.String("slack_token")
if len(token) == 0 {
return errors.New("missing slack token")
}
p.debug = debug
p.token = token
return nil
}
func (p *slackInput) Stream() (input.Conn, error) {
p.Lock()
defer p.Unlock()
if !p.running {
return nil, errors.New("not running")
}
// test auth
auth, err := p.api.AuthTest()
if err != nil {
return nil, err
}
rtm := p.api.NewRTM()
exit := make(chan bool)
go rtm.ManageConnection()
go func() {
select {
case <-p.exit:
select {
case <-exit:
return
default:
close(exit)
}
case <-exit:
}
rtm.Disconnect()
}()
conn := &slackConn{
auth: auth,
rtm: rtm,
exit: exit,
names: make(map[string]string),
}
go conn.run()
return conn, nil
}
func (p *slackInput) Start() error {
if len(p.token) == 0 {
return errors.New("missing slack token")
}
p.Lock()
defer p.Unlock()
if p.running {
return nil
}
api := slack.New(p.token, slack.OptionDebug(p.debug))
// test auth
_, err := api.AuthTest()
if err != nil {
return err
}
p.api = api
p.exit = make(chan bool)
p.running = true
return nil
}
func (p *slackInput) Stop() error {
p.Lock()
defer p.Unlock()
if !p.running {
return nil
}
close(p.exit)
p.running = false
return nil
}
func (p *slackInput) String() string {
return "slack"
}
func NewInput() input.Input {
return &slackInput{}
}

View File

@@ -1,18 +0,0 @@
# Telegram Messenger input for micro bot
[Telegram](https://telegram.org) support for micro bot based on [telegram-bot-api](https://github.com/go-telegram-bot-api/telegram-bot-api).
## Options
### --telegram_token (required)
Sets bot's token for interacting with API.
Head over to Telegram's [API documentation](https://core.telegram.org/bots/api)
to learn how to create bots and how the API works.
### --telegram_debug
Sets the debug flag to make the bot's output verbose.
### --telegram_whitelist
Sets a list of comma-separated nicknames (without @ symbol in the beginning) for interacting with bot. Only these users can use the bot.

View File

@@ -1,115 +0,0 @@
package telegram
import (
"errors"
"strings"
"sync"
"github.com/forestgiant/sliceutil"
"github.com/micro/go-micro/agent/input"
"github.com/micro/go-micro/util/log"
"gopkg.in/telegram-bot-api.v4"
)
type telegramConn struct {
input *telegramInput
recv <-chan tgbotapi.Update
exit chan bool
syncCond *sync.Cond
mutex sync.Mutex
}
func newConn(input *telegramInput) (*telegramConn, error) {
conn := &telegramConn{
input: input,
}
conn.syncCond = sync.NewCond(&conn.mutex)
go conn.run()
return conn, nil
}
func (tc *telegramConn) run() {
u := tgbotapi.NewUpdate(0)
u.Timeout = 60
updates, err := tc.input.api.GetUpdatesChan(u)
if err != nil {
return
}
tc.recv = updates
tc.syncCond.Signal()
for {
select {
case <-tc.exit:
return
}
}
}
func (tc *telegramConn) Close() error {
return nil
}
func (tc *telegramConn) Recv(event *input.Event) error {
if event == nil {
return errors.New("event cannot be nil")
}
for {
if tc.recv == nil {
tc.mutex.Lock()
tc.syncCond.Wait()
}
update := <-tc.recv
if update.Message == nil || (len(tc.input.whitelist) > 0 && !sliceutil.Contains(tc.input.whitelist, update.Message.From.UserName)) {
continue
}
if event.Meta == nil {
event.Meta = make(map[string]interface{})
}
event.Type = input.TextEvent
event.From = update.Message.From.UserName
event.To = tc.input.api.Self.UserName
event.Data = []byte(update.Message.Text)
event.Meta["chatId"] = update.Message.Chat.ID
event.Meta["chatType"] = update.Message.Chat.Type
event.Meta["messageId"] = update.Message.MessageID
return nil
}
}
func (tc *telegramConn) Send(event *input.Event) error {
messageText := strings.TrimSpace(string(event.Data))
chatId := event.Meta["chatId"].(int64)
chatType := ChatType(event.Meta["chatType"].(string))
msgConfig := tgbotapi.NewMessage(chatId, messageText)
msgConfig.ParseMode = tgbotapi.ModeHTML
if sliceutil.Contains([]ChatType{Group, Supergroup}, chatType) {
msgConfig.ReplyToMessageID = event.Meta["messageId"].(int)
}
_, err := tc.input.api.Send(msgConfig)
if err != nil {
// probably it could be because of nested HTML tags -- telegram doesn't allow nested tags
log.Log("[telegram][Send] error:", err)
msgConfig.Text = "This bot couldn't send the response (Internal error)"
tc.input.api.Send(msgConfig)
}
return nil
}

View File

@@ -1,101 +0,0 @@
package telegram
import (
"errors"
"strings"
"sync"
"github.com/micro/cli"
"github.com/micro/go-micro/agent/input"
"gopkg.in/telegram-bot-api.v4"
)
type telegramInput struct {
sync.Mutex
debug bool
token string
whitelist []string
api *tgbotapi.BotAPI
}
type ChatType string
const (
Private ChatType = "private"
Group ChatType = "group"
Supergroup ChatType = "supergroup"
)
func init() {
input.Inputs["telegram"] = &telegramInput{}
}
func (ti *telegramInput) Flags() []cli.Flag {
return []cli.Flag{
cli.BoolFlag{
Name: "telegram_debug",
EnvVar: "MICRO_TELEGRAM_DEBUG",
Usage: "Telegram debug output",
},
cli.StringFlag{
Name: "telegram_token",
EnvVar: "MICRO_TELEGRAM_TOKEN",
Usage: "Telegram token",
},
cli.StringFlag{
Name: "telegram_whitelist",
EnvVar: "MICRO_TELEGRAM_WHITELIST",
Usage: "Telegram bot's users (comma-separated values)",
},
}
}
func (ti *telegramInput) Init(ctx *cli.Context) error {
ti.debug = ctx.Bool("telegram_debug")
ti.token = ctx.String("telegram_token")
whitelist := ctx.String("telegram_whitelist")
if whitelist != "" {
ti.whitelist = strings.Split(whitelist, ",")
}
if len(ti.token) == 0 {
return errors.New("missing telegram token")
}
return nil
}
func (ti *telegramInput) Stream() (input.Conn, error) {
ti.Lock()
defer ti.Unlock()
return newConn(ti)
}
func (ti *telegramInput) Start() error {
ti.Lock()
defer ti.Unlock()
api, err := tgbotapi.NewBotAPI(ti.token)
if err != nil {
return err
}
ti.api = api
api.Debug = ti.debug
return nil
}
func (ti *telegramInput) Stop() error {
return nil
}
func (p *telegramInput) String() string {
return "telegram"
}

View File

@@ -1,118 +0,0 @@
// Code generated by protoc-gen-micro. DO NOT EDIT.
// source: github.com/micro/go-bot/proto/bot.proto
/*
Package go_micro_bot is a generated protocol buffer package.
It is generated from these files:
github.com/micro/go-bot/proto/bot.proto
It has these top-level messages:
HelpRequest
HelpResponse
ExecRequest
ExecResponse
*/
package go_micro_bot
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import (
context "context"
client "github.com/micro/go-micro/client"
server "github.com/micro/go-micro/server"
)
// 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
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ client.Option
var _ server.Option
// Client API for Command service
type CommandService interface {
Help(ctx context.Context, in *HelpRequest, opts ...client.CallOption) (*HelpResponse, error)
Exec(ctx context.Context, in *ExecRequest, opts ...client.CallOption) (*ExecResponse, error)
}
type commandService struct {
c client.Client
name string
}
func NewCommandService(name string, c client.Client) CommandService {
if c == nil {
c = client.NewClient()
}
if len(name) == 0 {
name = "go.micro.bot"
}
return &commandService{
c: c,
name: name,
}
}
func (c *commandService) Help(ctx context.Context, in *HelpRequest, opts ...client.CallOption) (*HelpResponse, error) {
req := c.c.NewRequest(c.name, "Command.Help", in)
out := new(HelpResponse)
err := c.c.Call(ctx, req, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *commandService) Exec(ctx context.Context, in *ExecRequest, opts ...client.CallOption) (*ExecResponse, error) {
req := c.c.NewRequest(c.name, "Command.Exec", in)
out := new(ExecResponse)
err := c.c.Call(ctx, req, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// Server API for Command service
type CommandHandler interface {
Help(context.Context, *HelpRequest, *HelpResponse) error
Exec(context.Context, *ExecRequest, *ExecResponse) error
}
func RegisterCommandHandler(s server.Server, hdlr CommandHandler, opts ...server.HandlerOption) error {
type _command interface {
Help(ctx context.Context, in *HelpRequest, out *HelpResponse) error
Exec(ctx context.Context, in *ExecRequest, out *ExecResponse) error
}
type Command struct {
_command
}
h := &commandHandler{hdlr}
return s.Handle(s.NewHandler(&Command{h}, opts...))
}
type commandHandler struct {
CommandHandler
}
func (h *commandHandler) Help(ctx context.Context, in *HelpRequest, out *HelpResponse) error {
return h.CommandHandler.Help(ctx, in, out)
}
func (h *commandHandler) Exec(ctx context.Context, in *ExecRequest, out *ExecResponse) error {
return h.CommandHandler.Exec(ctx, in, out)
}

View File

@@ -1,210 +0,0 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: github.com/micro/go-bot/proto/bot.proto
package go_micro_bot
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
// 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 HelpRequest struct {
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *HelpRequest) Reset() { *m = HelpRequest{} }
func (m *HelpRequest) String() string { return proto.CompactTextString(m) }
func (*HelpRequest) ProtoMessage() {}
func (*HelpRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_bot_654832eab83ed4b5, []int{0}
}
func (m *HelpRequest) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_HelpRequest.Unmarshal(m, b)
}
func (m *HelpRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_HelpRequest.Marshal(b, m, deterministic)
}
func (dst *HelpRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_HelpRequest.Merge(dst, src)
}
func (m *HelpRequest) XXX_Size() int {
return xxx_messageInfo_HelpRequest.Size(m)
}
func (m *HelpRequest) XXX_DiscardUnknown() {
xxx_messageInfo_HelpRequest.DiscardUnknown(m)
}
var xxx_messageInfo_HelpRequest proto.InternalMessageInfo
type HelpResponse struct {
Usage string `protobuf:"bytes,1,opt,name=usage,proto3" json:"usage,omitempty"`
Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *HelpResponse) Reset() { *m = HelpResponse{} }
func (m *HelpResponse) String() string { return proto.CompactTextString(m) }
func (*HelpResponse) ProtoMessage() {}
func (*HelpResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_bot_654832eab83ed4b5, []int{1}
}
func (m *HelpResponse) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_HelpResponse.Unmarshal(m, b)
}
func (m *HelpResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_HelpResponse.Marshal(b, m, deterministic)
}
func (dst *HelpResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_HelpResponse.Merge(dst, src)
}
func (m *HelpResponse) XXX_Size() int {
return xxx_messageInfo_HelpResponse.Size(m)
}
func (m *HelpResponse) XXX_DiscardUnknown() {
xxx_messageInfo_HelpResponse.DiscardUnknown(m)
}
var xxx_messageInfo_HelpResponse proto.InternalMessageInfo
func (m *HelpResponse) GetUsage() string {
if m != nil {
return m.Usage
}
return ""
}
func (m *HelpResponse) GetDescription() string {
if m != nil {
return m.Description
}
return ""
}
type ExecRequest struct {
Args []string `protobuf:"bytes,1,rep,name=args,proto3" json:"args,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *ExecRequest) Reset() { *m = ExecRequest{} }
func (m *ExecRequest) String() string { return proto.CompactTextString(m) }
func (*ExecRequest) ProtoMessage() {}
func (*ExecRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_bot_654832eab83ed4b5, []int{2}
}
func (m *ExecRequest) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_ExecRequest.Unmarshal(m, b)
}
func (m *ExecRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_ExecRequest.Marshal(b, m, deterministic)
}
func (dst *ExecRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_ExecRequest.Merge(dst, src)
}
func (m *ExecRequest) XXX_Size() int {
return xxx_messageInfo_ExecRequest.Size(m)
}
func (m *ExecRequest) XXX_DiscardUnknown() {
xxx_messageInfo_ExecRequest.DiscardUnknown(m)
}
var xxx_messageInfo_ExecRequest proto.InternalMessageInfo
func (m *ExecRequest) GetArgs() []string {
if m != nil {
return m.Args
}
return nil
}
type ExecResponse struct {
Result []byte `protobuf:"bytes,1,opt,name=result,proto3" json:"result,omitempty"`
Error string `protobuf:"bytes,2,opt,name=error,proto3" json:"error,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *ExecResponse) Reset() { *m = ExecResponse{} }
func (m *ExecResponse) String() string { return proto.CompactTextString(m) }
func (*ExecResponse) ProtoMessage() {}
func (*ExecResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_bot_654832eab83ed4b5, []int{3}
}
func (m *ExecResponse) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_ExecResponse.Unmarshal(m, b)
}
func (m *ExecResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_ExecResponse.Marshal(b, m, deterministic)
}
func (dst *ExecResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_ExecResponse.Merge(dst, src)
}
func (m *ExecResponse) XXX_Size() int {
return xxx_messageInfo_ExecResponse.Size(m)
}
func (m *ExecResponse) XXX_DiscardUnknown() {
xxx_messageInfo_ExecResponse.DiscardUnknown(m)
}
var xxx_messageInfo_ExecResponse proto.InternalMessageInfo
func (m *ExecResponse) GetResult() []byte {
if m != nil {
return m.Result
}
return nil
}
func (m *ExecResponse) GetError() string {
if m != nil {
return m.Error
}
return ""
}
func init() {
proto.RegisterType((*HelpRequest)(nil), "go.micro.bot.HelpRequest")
proto.RegisterType((*HelpResponse)(nil), "go.micro.bot.HelpResponse")
proto.RegisterType((*ExecRequest)(nil), "go.micro.bot.ExecRequest")
proto.RegisterType((*ExecResponse)(nil), "go.micro.bot.ExecResponse")
}
func init() {
proto.RegisterFile("github.com/micro/go-bot/proto/bot.proto", fileDescriptor_bot_654832eab83ed4b5)
}
var fileDescriptor_bot_654832eab83ed4b5 = []byte{
// 246 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0x90, 0x41, 0x4b, 0xc4, 0x30,
0x10, 0x85, 0xb7, 0xba, 0xae, 0xec, 0xb4, 0x5e, 0x82, 0x48, 0xdd, 0x53, 0xcd, 0xc5, 0xbd, 0x98,
0x82, 0x5e, 0x05, 0x0f, 0xa2, 0x78, 0xee, 0x3f, 0x68, 0xba, 0x43, 0x2c, 0x6c, 0x3b, 0x35, 0x99,
0x82, 0xff, 0xc1, 0x3f, 0x2d, 0x4d, 0x72, 0x08, 0xcb, 0xde, 0xe6, 0x65, 0x86, 0xf7, 0xbe, 0x17,
0x78, 0x34, 0x3d, 0x7f, 0xcf, 0x5a, 0x75, 0x34, 0xd4, 0x43, 0xdf, 0x59, 0xaa, 0x0d, 0x3d, 0x69,
0xe2, 0x7a, 0xb2, 0xc4, 0x54, 0x6b, 0x62, 0xe5, 0x27, 0x51, 0x18, 0x52, 0xfe, 0x40, 0x69, 0x62,
0x79, 0x03, 0xf9, 0x17, 0x1e, 0xa7, 0x06, 0x7f, 0x66, 0x74, 0x2c, 0x3f, 0xa1, 0x08, 0xd2, 0x4d,
0x34, 0x3a, 0x14, 0xb7, 0x70, 0x35, 0xbb, 0xd6, 0x60, 0x99, 0x55, 0xd9, 0x7e, 0xdb, 0x04, 0x21,
0x2a, 0xc8, 0x0f, 0xe8, 0x3a, 0xdb, 0x4f, 0xdc, 0xd3, 0x58, 0x5e, 0xf8, 0x5d, 0xfa, 0x24, 0x1f,
0x20, 0xff, 0xf8, 0xc5, 0x2e, 0xda, 0x0a, 0x01, 0xeb, 0xd6, 0x1a, 0x57, 0x66, 0xd5, 0xe5, 0x7e,
0xdb, 0xf8, 0x59, 0xbe, 0x42, 0x11, 0x4e, 0x62, 0xd4, 0x1d, 0x6c, 0x2c, 0xba, 0xf9, 0xc8, 0x3e,
0xab, 0x68, 0xa2, 0x5a, 0x10, 0xd0, 0x5a, 0xb2, 0x31, 0x26, 0x88, 0xe7, 0xbf, 0x0c, 0xae, 0xdf,
0x69, 0x18, 0xda, 0xf1, 0x20, 0xde, 0x60, 0xbd, 0x40, 0x8b, 0x7b, 0x95, 0x56, 0x53, 0x49, 0xaf,
0xdd, 0xee, 0xdc, 0x2a, 0x04, 0xcb, 0xd5, 0x62, 0xb0, 0xa0, 0x9c, 0x1a, 0x24, 0x0d, 0x4e, 0x0d,
0x52, 0x72, 0xb9, 0xd2, 0x1b, 0xff, 0xb5, 0x2f, 0xff, 0x01, 0x00, 0x00, 0xff, 0xff, 0xcb, 0x77,
0xdf, 0x28, 0x85, 0x01, 0x00, 0x00,
}

View File

@@ -1,25 +0,0 @@
syntax = "proto3";
package go.micro.bot;
service Command {
rpc Help(HelpRequest) returns (HelpResponse) {};
rpc Exec(ExecRequest) returns (ExecResponse) {};
}
message HelpRequest {
}
message HelpResponse {
string usage = 1;
string description = 2;
}
message ExecRequest {
repeated string args = 1;
}
message ExecResponse {
bytes result = 1;
string error = 2;
}

View File

@@ -5,50 +5,61 @@ import (
"regexp"
"strings"
"github.com/micro/go-micro/registry"
"github.com/micro/go-micro/server"
"github.com/unistack-org/micro/v3/metadata"
"github.com/unistack-org/micro/v3/register"
"github.com/unistack-org/micro/v3/server"
)
// Api interface
type Api interface {
// Initialise options
Init(...Option) error
// Get the options
Options() Options
// Register a http handler
Register(*Endpoint) error
// Register a route
Deregister(*Endpoint) error
// Implementation of api
String() string
}
// Options holds the options
type Options struct{}
// Option func signature
type Option func(*Options) error
// Endpoint is a mapping between an RPC method and HTTP endpoint
type Endpoint struct {
// RPC Method e.g. Greeter.Hello
// Name Greeter.Hello
Name string
// Description e.g what's this endpoint for
// Desciption for endpoint
Description string
// API Handler e.g rpc, proxy
// Handler e.g rpc, proxy
Handler string
// HTTP Host e.g example.com
// Body destination
// "*" or "" - top level message value
// "string" - inner message value
Body string
// Host e.g example.com
Host []string
// HTTP Methods e.g GET, POST
// Method e.g GET, POST
Method []string
// HTTP Path e.g /greeter. Expect POSIX regex
// Path e.g /greeter. Expect POSIX regex
Path []string
// Stream flag
Stream bool
}
// Service represents an API service
type Service struct {
// Name of service
Name string
// The endpoint for this service
// Endpoint for this service
Endpoint *Endpoint
// Versions of this service
Services []*registry.Service
}
func strip(s string) string {
return strings.TrimSpace(s)
}
func slice(s string) []string {
var sl []string
for _, p := range strings.Split(s, ",") {
if str := strip(p); len(str) > 0 {
sl = append(sl, strip(p))
}
}
return sl
// Services that provides service
Services []*register.Service
}
// Encode encodes an endpoint to endpoint metadata
@@ -57,30 +68,47 @@ func Encode(e *Endpoint) map[string]string {
return nil
}
return map[string]string{
"endpoint": e.Name,
"description": e.Description,
"method": strings.Join(e.Method, ","),
"path": strings.Join(e.Path, ","),
"host": strings.Join(e.Host, ","),
"handler": e.Handler,
// endpoint map
ep := make(map[string]string)
// set vals only if they exist
set := func(k, v string) {
if len(v) == 0 {
return
}
ep[k] = v
}
set("endpoint", e.Name)
set("description", e.Description)
set("handler", e.Handler)
set("method", strings.Join(e.Method, ","))
set("path", strings.Join(e.Path, ","))
set("host", strings.Join(e.Host, ","))
set("body", e.Body)
return ep
}
// Decode decodes endpoint metadata into an endpoint
func Decode(e map[string]string) *Endpoint {
func Decode(e metadata.Metadata) *Endpoint {
if e == nil {
return nil
}
return &Endpoint{
Name: e["endpoint"],
Description: e["description"],
Method: slice(e["method"]),
Path: slice(e["path"]),
Host: slice(e["host"]),
Handler: e["handler"],
}
ep := &Endpoint{}
ep.Name, _ = e.Get("endpoint")
ep.Description, _ = e.Get("description")
epmethod, _ := e.Get("method")
ep.Method = []string{epmethod}
eppath, _ := e.Get("path")
ep.Path = []string{eppath}
ephost, _ := e.Get("host")
ep.Host = []string{ephost}
ep.Handler, _ = e.Get("handler")
ep.Body, _ = e.Get("body")
return ep
}
// Validate validates an endpoint to guarantee it won't blow up when being served
@@ -94,9 +122,18 @@ func Validate(e *Endpoint) error {
}
for _, p := range e.Path {
_, err := regexp.CompilePOSIX(p)
if err != nil {
return err
ps := p[0]
pe := p[len(p)-1]
if ps == '^' && pe == '$' {
_, err := regexp.CompilePOSIX(p)
if err != nil {
return err
}
} else if ps == '^' && pe != '$' {
return errors.New("invalid path")
} else if ps != '^' && pe == '$' {
return errors.New("invalid path")
}
}

View File

@@ -5,6 +5,7 @@ import (
"testing"
)
//nolint:gocyclo
func TestEncoding(t *testing.T) {
testData := []*Endpoint{
nil,
@@ -111,3 +112,42 @@ func TestEncoding(t *testing.T) {
}
}
}
func TestValidate(t *testing.T) {
epPcre := &Endpoint{
Name: "Foo.Bar",
Description: "A test endpoint",
Handler: "meta",
Host: []string{"foo.com"},
Method: []string{"GET"},
Path: []string{"^/test/?$"},
}
if err := Validate(epPcre); err != nil {
t.Fatal(err)
}
epGpath := &Endpoint{
Name: "Foo.Bar",
Description: "A test endpoint",
Handler: "meta",
Host: []string{"foo.com"},
Method: []string{"GET"},
Path: []string{"/test/{id}"},
}
if err := Validate(epGpath); err != nil {
t.Fatal(err)
}
epPcreInvalid := &Endpoint{
Name: "Foo.Bar",
Description: "A test endpoint",
Handler: "meta",
Host: []string{"foo.com"},
Method: []string{"GET"},
Path: []string{"/test/?$"},
}
if err := Validate(epPcreInvalid); err == nil {
t.Fatalf("invalid pcre %v", epPcreInvalid.Path[0])
}
}

View File

@@ -1,117 +0,0 @@
// Package api provides an http-rpc handler which provides the entire http request over rpc
package api
import (
"net/http"
goapi "github.com/micro/go-micro/api"
"github.com/micro/go-micro/api/handler"
api "github.com/micro/go-micro/api/proto"
"github.com/micro/go-micro/client"
"github.com/micro/go-micro/client/selector"
"github.com/micro/go-micro/errors"
"github.com/micro/go-micro/util/ctx"
)
type apiHandler struct {
opts handler.Options
s *goapi.Service
}
const (
Handler = "api"
)
// API handler is the default handler which takes api.Request and returns api.Response
func (a *apiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
request, err := requestToProto(r)
if err != nil {
er := errors.InternalServerError("go.micro.api", err.Error())
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(500)
w.Write([]byte(er.Error()))
return
}
var service *goapi.Service
if a.s != nil {
// we were given the service
service = a.s
} else if a.opts.Router != nil {
// try get service from router
s, err := a.opts.Router.Route(r)
if err != nil {
er := errors.InternalServerError("go.micro.api", err.Error())
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(500)
w.Write([]byte(er.Error()))
return
}
service = s
} else {
// we have no way of routing the request
er := errors.InternalServerError("go.micro.api", "no route found")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(500)
w.Write([]byte(er.Error()))
return
}
// create request and response
c := a.opts.Service.Client()
req := c.NewRequest(service.Name, service.Endpoint.Name, request)
rsp := &api.Response{}
// create the context from headers
cx := ctx.FromRequest(r)
// create strategy
so := selector.WithStrategy(strategy(service.Services))
if err := c.Call(cx, req, rsp, client.WithSelectOption(so)); err != nil {
w.Header().Set("Content-Type", "application/json")
ce := errors.Parse(err.Error())
switch ce.Code {
case 0:
w.WriteHeader(500)
default:
w.WriteHeader(int(ce.Code))
}
w.Write([]byte(ce.Error()))
return
} else if rsp.StatusCode == 0 {
rsp.StatusCode = http.StatusOK
}
for _, header := range rsp.GetHeader() {
for _, val := range header.Values {
w.Header().Add(header.Key, val)
}
}
if len(w.Header().Get("Content-Type")) == 0 {
w.Header().Set("Content-Type", "application/json")
}
w.WriteHeader(int(rsp.StatusCode))
w.Write([]byte(rsp.Body))
}
func (a *apiHandler) String() string {
return "api"
}
func NewHandler(opts ...handler.Option) handler.Handler {
options := handler.NewOptions(opts...)
return &apiHandler{
opts: options,
}
}
func WithService(s *goapi.Service, opts ...handler.Option) handler.Handler {
options := handler.NewOptions(opts...)
return &apiHandler{
opts: options,
s: s,
}
}

View File

@@ -1,107 +0,0 @@
package api
import (
"fmt"
"io/ioutil"
"mime"
"net"
"net/http"
"strings"
api "github.com/micro/go-micro/api/proto"
"github.com/micro/go-micro/client/selector"
"github.com/micro/go-micro/registry"
)
func requestToProto(r *http.Request) (*api.Request, error) {
if err := r.ParseForm(); err != nil {
return nil, fmt.Errorf("Error parsing form: %v", err)
}
req := &api.Request{
Path: r.URL.Path,
Method: r.Method,
Header: make(map[string]*api.Pair),
Get: make(map[string]*api.Pair),
Post: make(map[string]*api.Pair),
Url: r.URL.String(),
}
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
ct = "application/x-www-form-urlencoded"
r.Header.Set("Content-Type", ct)
}
switch ct {
case "application/x-www-form-urlencoded":
// expect form vals
default:
data, _ := ioutil.ReadAll(r.Body)
req.Body = string(data)
}
// Set X-Forwarded-For if it does not exist
if ip, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
if prior, ok := r.Header["X-Forwarded-For"]; ok {
ip = strings.Join(prior, ", ") + ", " + ip
}
// Set the header
req.Header["X-Forwarded-For"] = &api.Pair{
Key: "X-Forwarded-For",
Values: []string{ip},
}
}
// Host is stripped from net/http Headers so let's add it
req.Header["Host"] = &api.Pair{
Key: "Host",
Values: []string{r.Host},
}
// Get data
for key, vals := range r.URL.Query() {
header, ok := req.Get[key]
if !ok {
header = &api.Pair{
Key: key,
}
req.Get[key] = header
}
header.Values = vals
}
// Post data
for key, vals := range r.PostForm {
header, ok := req.Post[key]
if !ok {
header = &api.Pair{
Key: key,
}
req.Post[key] = header
}
header.Values = vals
}
for key, vals := range r.Header {
header, ok := req.Header[key]
if !ok {
header = &api.Pair{
Key: key,
}
req.Header[key] = header
}
header.Values = vals
}
return req, nil
}
// strategy is a hack for selection
func strategy(services []*registry.Service) selector.Strategy {
return func(_ []*registry.Service) selector.Next {
// ignore input to this function, use services above
return selector.Random(services)
}
}

View File

@@ -1,46 +0,0 @@
package api
import (
"net/http"
"net/url"
"testing"
)
func TestRequestToProto(t *testing.T) {
testData := []*http.Request{
{
Method: "GET",
Header: http.Header{
"Header": []string{"test"},
},
URL: &url.URL{
Scheme: "http",
Host: "localhost",
Path: "/foo/bar",
RawQuery: "param1=value1",
},
},
}
for _, d := range testData {
p, err := requestToProto(d)
if err != nil {
t.Fatal(err)
}
if p.Path != d.URL.Path {
t.Fatalf("Expected path %s got %s", d.URL.Path, p.Path)
}
if p.Method != d.Method {
t.Fatalf("Expected method %s got %s", d.Method, p.Method)
}
for k, v := range d.Header {
if val, ok := p.Header[k]; !ok {
t.Fatalf("Expected header %s", k)
} else {
if val.Values[0] != v[0] {
t.Fatalf("Expected val %s, got %s", val.Values[0], v[0])
}
}
}
}
}

View File

@@ -1,268 +0,0 @@
// Package broker provides a go-micro/broker handler
package broker
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/gorilla/websocket"
"github.com/micro/go-micro/api/handler"
"github.com/micro/go-micro/broker"
"github.com/micro/go-micro/util/log"
)
const (
Handler = "broker"
pingTime = (readDeadline * 9) / 10
readLimit = 16384
readDeadline = 60 * time.Second
writeDeadline = 10 * time.Second
)
type brokerHandler struct {
opts handler.Options
u websocket.Upgrader
}
type conn struct {
b broker.Broker
cType string
topic string
queue string
exit chan bool
sync.Mutex
ws *websocket.Conn
}
var (
once sync.Once
contentType = "text/plain"
)
func checkOrigin(r *http.Request) bool {
origin := r.Header["Origin"]
if len(origin) == 0 {
return true
}
u, err := url.Parse(origin[0])
if err != nil {
return false
}
return u.Host == r.Host
}
func (c *conn) close() {
select {
case <-c.exit:
return
default:
close(c.exit)
}
}
func (c *conn) readLoop() {
defer func() {
c.close()
c.ws.Close()
}()
// set read limit/deadline
c.ws.SetReadLimit(readLimit)
c.ws.SetReadDeadline(time.Now().Add(readDeadline))
// set close handler
ch := c.ws.CloseHandler()
c.ws.SetCloseHandler(func(code int, text string) error {
err := ch(code, text)
c.close()
return err
})
// set pong handler
c.ws.SetPongHandler(func(string) error {
c.ws.SetReadDeadline(time.Now().Add(readDeadline))
return nil
})
for {
_, message, err := c.ws.ReadMessage()
if err != nil {
return
}
c.b.Publish(c.topic, &broker.Message{
Header: map[string]string{"Content-Type": c.cType},
Body: message,
})
}
}
func (c *conn) write(mType int, data []byte) error {
c.Lock()
c.ws.SetWriteDeadline(time.Now().Add(writeDeadline))
err := c.ws.WriteMessage(mType, data)
c.Unlock()
return err
}
func (c *conn) writeLoop() {
ticker := time.NewTicker(pingTime)
var opts []broker.SubscribeOption
if len(c.queue) > 0 {
opts = append(opts, broker.Queue(c.queue))
}
subscriber, err := c.b.Subscribe(c.topic, func(p broker.Event) error {
b, err := json.Marshal(p.Message())
if err != nil {
return nil
}
return c.write(websocket.TextMessage, b)
}, opts...)
defer func() {
subscriber.Unsubscribe()
ticker.Stop()
c.ws.Close()
}()
if err != nil {
log.Log(err.Error())
return
}
for {
select {
case <-ticker.C:
if err := c.write(websocket.PingMessage, []byte{}); err != nil {
return
}
case <-c.exit:
return
}
}
}
func (b *brokerHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
br := b.opts.Service.Client().Options().Broker
// Setup the broker
once.Do(func() {
br.Init()
br.Connect()
})
// Parse
r.ParseForm()
topic := r.Form.Get("topic")
// Can't do anything without a topic
if len(topic) == 0 {
http.Error(w, "Topic not specified", 400)
return
}
// Post assumed to be Publish
if r.Method == "POST" {
// Create a broker message
msg := &broker.Message{
Header: make(map[string]string),
}
// Set header
for k, v := range r.Header {
msg.Header[k] = strings.Join(v, ", ")
}
// Read body
b, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
// Set body
msg.Body = b
// Publish
br.Publish(topic, msg)
return
}
// now back to our regularly scheduled programming
if r.Method != "GET" {
http.Error(w, "Method not allowed", 405)
return
}
queue := r.Form.Get("queue")
ws, err := b.u.Upgrade(w, r, nil)
if err != nil {
log.Log(err.Error())
return
}
cType := r.Header.Get("Content-Type")
if len(cType) == 0 {
cType = contentType
}
c := &conn{
b: br,
cType: cType,
topic: topic,
queue: queue,
exit: make(chan bool),
ws: ws,
}
go c.writeLoop()
c.readLoop()
}
func (b *brokerHandler) String() string {
return "broker"
}
func NewHandler(opts ...handler.Option) handler.Handler {
return &brokerHandler{
u: websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
ReadBufferSize: 1024,
WriteBufferSize: 1024,
},
opts: handler.NewOptions(opts...),
}
}
func WithCors(cors map[string]bool, opts ...handler.Option) handler.Handler {
return &brokerHandler{
u: websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
if origin := r.Header.Get("Origin"); cors[origin] {
return true
} else if len(origin) > 0 && cors["*"] {
return true
} else if checkOrigin(r) {
return true
}
return false
},
ReadBufferSize: 1024,
WriteBufferSize: 1024,
},
opts: handler.NewOptions(opts...),
}
}

View File

@@ -1,94 +0,0 @@
// Package cloudevents provides a cloudevents handler publishing the event using the go-micro/client
package cloudevents
import (
"net/http"
"path"
"regexp"
"strings"
"github.com/micro/go-micro/api/handler"
"github.com/micro/go-micro/util/ctx"
)
type event struct {
options handler.Options
}
var (
Handler = "cloudevents"
versionRe = regexp.MustCompilePOSIX("^v[0-9]+$")
)
func eventName(parts []string) string {
return strings.Join(parts, ".")
}
func evRoute(ns, p string) (string, string) {
p = path.Clean(p)
p = strings.TrimPrefix(p, "/")
if len(p) == 0 {
return ns, "event"
}
parts := strings.Split(p, "/")
// no path
if len(parts) == 0 {
// topic: namespace
// action: event
return strings.Trim(ns, "."), "event"
}
// Treat /v[0-9]+ as versioning
// /v1/foo/bar => topic: v1.foo action: bar
if len(parts) >= 2 && versionRe.Match([]byte(parts[0])) {
topic := ns + "." + strings.Join(parts[:2], ".")
action := eventName(parts[1:])
return topic, action
}
// /foo => topic: ns.foo action: foo
// /foo/bar => topic: ns.foo action: bar
topic := ns + "." + strings.Join(parts[:1], ".")
action := eventName(parts[1:])
return topic, action
}
func (e *event) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// request to topic:event
// create event
// publish to topic
topic, _ := evRoute(e.options.Namespace, r.URL.Path)
// create event
ev, err := FromRequest(r)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
// get client
c := e.options.Service.Client()
// create publication
p := c.NewMessage(topic, ev)
// publish event
if err := c.Publish(ctx.FromRequest(r), p); err != nil {
http.Error(w, err.Error(), 500)
return
}
}
func (e *event) String() string {
return "cloudevents"
}
func NewHandler(opts ...handler.Option) handler.Handler {
return &event{
options: handler.NewOptions(opts...),
}
}

View File

@@ -1,282 +0,0 @@
/*
* From: https://github.com/serverless/event-gateway/blob/master/event/event.go
* Modified: Strip to handler requirements
*
* Copyright 2017 Serverless, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package cloudevents
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"mime"
"net/http"
"strings"
"time"
"unicode"
"github.com/google/uuid"
"gopkg.in/go-playground/validator.v9"
)
const (
// TransformationVersion is indicative of the revision of how Event Gateway transforms a request into CloudEvents format.
TransformationVersion = "0.1"
// CloudEventsVersion currently supported by Event Gateway
CloudEventsVersion = "0.1"
)
// Event is a default event structure. All data that passes through the Event Gateway
// is formatted to a format defined CloudEvents v0.1 spec.
type Event struct {
EventType string `json:"eventType" validate:"required"`
EventTypeVersion string `json:"eventTypeVersion,omitempty"`
CloudEventsVersion string `json:"cloudEventsVersion" validate:"required"`
Source string `json:"source" validate:"uri,required"`
EventID string `json:"eventID" validate:"required"`
EventTime *time.Time `json:"eventTime,omitempty"`
SchemaURL string `json:"schemaURL,omitempty"`
Extensions map[string]interface{} `json:"extensions,omitempty"`
ContentType string `json:"contentType,omitempty"`
Data interface{} `json:"data"`
}
// New return new instance of Event.
func New(eventType string, mimeType string, payload interface{}) *Event {
now := time.Now()
event := &Event{
EventType: eventType,
CloudEventsVersion: CloudEventsVersion,
Source: "https://micro.mu",
EventID: uuid.New().String(),
EventTime: &now,
ContentType: mimeType,
Data: payload,
Extensions: map[string]interface{}{
"eventgateway": map[string]interface{}{
"transformed": "true",
"transformation-version": TransformationVersion,
},
},
}
event.Data = normalizePayload(event.Data, event.ContentType)
return event
}
// FromRequest takes an HTTP request and returns an Event along with path. Most of the implementation
// is based on https://github.com/cloudevents/spec/blob/master/http-transport-binding.md.
// This function also supports legacy mode where event type is sent in Event header.
func FromRequest(r *http.Request) (*Event, error) {
contentType := r.Header.Get("Content-Type")
mimeType, _, err := mime.ParseMediaType(contentType)
if err != nil {
if err.Error() != "mime: no media type" {
return nil, err
}
mimeType = "application/octet-stream"
}
// Read request body
body := []byte{}
if r.Body != nil {
body, err = ioutil.ReadAll(r.Body)
if err != nil {
return nil, err
}
}
var event *Event
if mimeType == mimeCloudEventsJSON { // CloudEvents Structured Content Mode
return parseAsCloudEvent(mimeType, body)
} else if isCloudEventsBinaryContentMode(r.Header) { // CloudEvents Binary Content Mode
return parseAsCloudEventBinary(r.Header, body)
} else if isLegacyMode(r.Header) {
if mimeType == mimeJSON { // CloudEvent in Legacy Mode
event, err = parseAsCloudEvent(mimeType, body)
if err != nil {
return New(string(r.Header.Get("event")), mimeType, body), nil
}
return event, err
}
return New(string(r.Header.Get("event")), mimeType, body), nil
}
return New("http.request", mimeJSON, newHTTPRequestData(r, body)), nil
}
// Validate Event struct
func (e *Event) Validate() error {
validate := validator.New()
err := validate.Struct(e)
if err != nil {
return fmt.Errorf("CloudEvent not valid: %v", err)
}
return nil
}
func isLegacyMode(headers http.Header) bool {
if headers.Get("Event") != "" {
return true
}
return false
}
func isCloudEventsBinaryContentMode(headers http.Header) bool {
if headers.Get("CE-EventType") != "" &&
headers.Get("CE-CloudEventsVersion") != "" &&
headers.Get("CE-Source") != "" &&
headers.Get("CE-EventID") != "" {
return true
}
return false
}
func parseAsCloudEventBinary(headers http.Header, payload interface{}) (*Event, error) {
event := &Event{
EventType: headers.Get("CE-EventType"),
EventTypeVersion: headers.Get("CE-EventTypeVersion"),
CloudEventsVersion: headers.Get("CE-CloudEventsVersion"),
Source: headers.Get("CE-Source"),
EventID: headers.Get("CE-EventID"),
ContentType: headers.Get("Content-Type"),
Data: payload,
}
err := event.Validate()
if err != nil {
return nil, err
}
if headers.Get("CE-EventTime") != "" {
val, err := time.Parse(time.RFC3339, headers.Get("CE-EventTime"))
if err != nil {
return nil, err
}
event.EventTime = &val
}
if val := headers.Get("CE-SchemaURL"); len(val) > 0 {
event.SchemaURL = val
}
event.Extensions = map[string]interface{}{}
for key, val := range flatten(headers) {
if strings.HasPrefix(key, "Ce-X-") {
key = strings.TrimLeft(key, "Ce-X-")
// Make first character lowercase
runes := []rune(key)
runes[0] = unicode.ToLower(runes[0])
event.Extensions[string(runes)] = val
}
}
event.Data = normalizePayload(event.Data, event.ContentType)
return event, nil
}
func flatten(h http.Header) map[string]string {
headers := map[string]string{}
for key, header := range h {
headers[key] = header[0]
if len(header) > 1 {
headers[key] = strings.Join(header, ", ")
}
}
return headers
}
func parseAsCloudEvent(mime string, payload interface{}) (*Event, error) {
body, ok := payload.([]byte)
if ok {
event := &Event{}
err := json.Unmarshal(body, event)
if err != nil {
return nil, err
}
err = event.Validate()
if err != nil {
return nil, err
}
event.Data = normalizePayload(event.Data, event.ContentType)
return event, nil
}
return nil, errors.New("couldn't cast to []byte")
}
const (
mimeJSON = "application/json"
mimeFormMultipart = "multipart/form-data"
mimeFormURLEncoded = "application/x-www-form-urlencoded"
mimeCloudEventsJSON = "application/cloudevents+json"
)
// normalizePayload takes anything, checks if it's []byte array and depending on provided mime
// type converts it to either string or map[string]interface to avoid having base64 string after
// JSON marshaling.
func normalizePayload(payload interface{}, mime string) interface{} {
if bytePayload, ok := payload.([]byte); ok && len(bytePayload) > 0 {
switch {
case mime == mimeJSON || strings.HasSuffix(mime, "+json"):
var result map[string]interface{}
err := json.Unmarshal(bytePayload, &result)
if err != nil {
return payload
}
return result
case strings.HasPrefix(mime, mimeFormMultipart), mime == mimeFormURLEncoded:
return string(bytePayload)
}
}
return payload
}
// HTTPRequestData is a event schema used for sending events to HTTP subscriptions.
type HTTPRequestData struct {
Headers map[string]string `json:"headers"`
Query map[string][]string `json:"query"`
Body interface{} `json:"body"`
Host string `json:"host"`
Path string `json:"path"`
Method string `json:"method"`
Params map[string]string `json:"params"`
}
// NewHTTPRequestData returns a new instance of HTTPRequestData
func newHTTPRequestData(r *http.Request, eventData interface{}) *HTTPRequestData {
req := &HTTPRequestData{
Headers: flatten(r.Header),
Query: r.URL.Query(),
Body: eventData,
Host: r.Host,
Path: r.URL.Path,
Method: r.Method,
}
req.Body = normalizePayload(req.Body, r.Header.Get("content-type"))
return req
}

View File

@@ -1,122 +0,0 @@
// Package event provides a handler which publishes an event
package event
import (
"fmt"
"io/ioutil"
"net/http"
"path"
"regexp"
"strings"
"time"
"github.com/google/uuid"
"github.com/micro/go-micro/api/handler"
proto "github.com/micro/go-micro/api/proto"
"github.com/micro/go-micro/util/ctx"
)
type event struct {
options handler.Options
}
var (
Handler = "event"
versionRe = regexp.MustCompilePOSIX("^v[0-9]+$")
)
func eventName(parts []string) string {
return strings.Join(parts, ".")
}
func evRoute(ns, p string) (string, string) {
p = path.Clean(p)
p = strings.TrimPrefix(p, "/")
if len(p) == 0 {
return ns, "event"
}
parts := strings.Split(p, "/")
// no path
if len(parts) == 0 {
// topic: namespace
// action: event
return strings.Trim(ns, "."), "event"
}
// Treat /v[0-9]+ as versioning
// /v1/foo/bar => topic: v1.foo action: bar
if len(parts) >= 2 && versionRe.Match([]byte(parts[0])) {
topic := ns + "." + strings.Join(parts[:2], ".")
action := eventName(parts[1:])
return topic, action
}
// /foo => topic: ns.foo action: foo
// /foo/bar => topic: ns.foo action: bar
topic := ns + "." + strings.Join(parts[:1], ".")
action := eventName(parts[1:])
return topic, action
}
func (e *event) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// request to topic:event
// create event
// publish to topic
topic, action := evRoute(e.options.Namespace, r.URL.Path)
// create event
ev := &proto.Event{
Name: action,
// TODO: dedupe event
Id: fmt.Sprintf("%s-%s-%s", topic, action, uuid.New().String()),
Header: make(map[string]*proto.Pair),
Timestamp: time.Now().Unix(),
}
// set headers
for key, vals := range r.Header {
header, ok := ev.Header[key]
if !ok {
header = &proto.Pair{
Key: key,
}
ev.Header[key] = header
}
header.Values = vals
}
// set body
b, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
ev.Data = string(b)
// get client
c := e.options.Service.Client()
// create publication
p := c.NewMessage(topic, ev)
// publish event
if err := c.Publish(ctx.FromRequest(r), p); err != nil {
http.Error(w, err.Error(), 500)
return
}
}
func (e *event) String() string {
return "event"
}
func NewHandler(opts ...handler.Option) handler.Handler {
return &event{
options: handler.NewOptions(opts...),
}
}

View File

@@ -1,16 +0,0 @@
// Package file serves file relative to the current directory
package file
import (
"net/http"
)
type Handler struct{}
func (h *Handler) Serve(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "."+r.URL.Path)
}
func (h *Handler) String() string {
return "file"
}

View File

@@ -1,100 +0,0 @@
// Package http is a http reverse proxy handler
package http
import (
"errors"
"fmt"
"net/http"
"net/http/httputil"
"net/url"
"github.com/micro/go-micro/api"
"github.com/micro/go-micro/api/handler"
"github.com/micro/go-micro/client/selector"
)
const (
Handler = "http"
)
type httpHandler struct {
options handler.Options
// set with different initialiser
s *api.Service
}
func (h *httpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
service, err := h.getService(r)
if err != nil {
w.WriteHeader(500)
return
}
if len(service) == 0 {
w.WriteHeader(404)
return
}
rp, err := url.Parse(service)
if err != nil {
w.WriteHeader(500)
return
}
httputil.NewSingleHostReverseProxy(rp).ServeHTTP(w, r)
}
// getService returns the service for this request from the selector
func (h *httpHandler) getService(r *http.Request) (string, error) {
var service *api.Service
if h.s != nil {
// we were given the service
service = h.s
} else if h.options.Router != nil {
// try get service from router
s, err := h.options.Router.Route(r)
if err != nil {
return "", err
}
service = s
} else {
// we have no way of routing the request
return "", errors.New("no route found")
}
// create a random selector
next := selector.Random(service.Services)
// get the next node
s, err := next()
if err != nil {
return "", nil
}
return fmt.Sprintf("http://%s", s.Address), nil
}
func (h *httpHandler) String() string {
return "http"
}
// NewHandler returns a http proxy handler
func NewHandler(opts ...handler.Option) handler.Handler {
options := handler.NewOptions(opts...)
return &httpHandler{
options: options,
}
}
// WithService creates a handler with a service
func WithService(s *api.Service, opts ...handler.Option) handler.Handler {
options := handler.NewOptions(opts...)
return &httpHandler{
options: options,
s: s,
}
}

View File

@@ -1,122 +0,0 @@
package http
import (
"net"
"net/http"
"net/http/httptest"
"testing"
"github.com/micro/go-micro/api/handler"
"github.com/micro/go-micro/api/router"
regRouter "github.com/micro/go-micro/api/router/registry"
"github.com/micro/go-micro/config/cmd"
"github.com/micro/go-micro/registry"
"github.com/micro/go-micro/registry/memory"
)
func testHttp(t *testing.T, path, service, ns string) {
r := memory.NewRegistry()
cmd.DefaultCmd = cmd.NewCmd(cmd.Registry(&r))
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer l.Close()
s := &registry.Service{
Name: service,
Nodes: []*registry.Node{
{
Id: service + "-1",
Address: l.Addr().String(),
},
},
}
r.Register(s)
defer r.Deregister(s)
// setup the test handler
m := http.NewServeMux()
m.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`you got served`))
})
// start http test serve
go http.Serve(l, m)
// create new request and writer
w := httptest.NewRecorder()
req, err := http.NewRequest("POST", path, nil)
if err != nil {
t.Fatal(err)
}
// initialise the handler
rt := regRouter.NewRouter(
router.WithHandler("http"),
router.WithNamespace(ns),
)
p := NewHandler(handler.WithRouter(rt))
// execute the handler
p.ServeHTTP(w, req)
if w.Code != 200 {
t.Fatalf("Expected 200 response got %d %s", w.Code, w.Body.String())
}
if w.Body.String() != "you got served" {
t.Fatalf("Expected body: you got served. Got: %s", w.Body.String())
}
}
func TestHttpHandler(t *testing.T) {
testData := []struct {
path string
service string
namespace string
}{
{
"/test/foo",
"go.micro.api.test",
"go.micro.api",
},
{
"/test/foo/baz",
"go.micro.api.test",
"go.micro.api",
},
{
"/v1/foo",
"go.micro.api.v1.foo",
"go.micro.api",
},
{
"/v1/foo/bar",
"go.micro.api.v1.foo",
"go.micro.api",
},
{
"/v2/baz",
"go.micro.api.v2.baz",
"go.micro.api",
},
{
"/v2/baz/bar",
"go.micro.api.v2.baz",
"go.micro.api",
},
{
"/v2/baz/bar",
"v2.baz",
"",
},
}
for _, d := range testData {
testHttp(t, d.path, d.service, d.namespace)
}
}

View File

@@ -1,30 +1,40 @@
package handler
import (
"github.com/micro/go-micro"
"github.com/micro/go-micro/api/router"
"github.com/unistack-org/micro/v3/api/router"
"github.com/unistack-org/micro/v3/client"
"github.com/unistack-org/micro/v3/logger"
)
var (
// DefaultMaxRecvSize specifies max recv size for handler
DefaultMaxRecvSize int64 = 1024 * 1024 * 100 // 10Mb
)
// Options struct holds handler options
type Options struct {
Namespace string
Router router.Router
Service micro.Service
Router router.Router
Client client.Client
Logger logger.Logger
Namespace string
MaxRecvSize int64
}
// Option func signature
type Option func(o *Options)
// NewOptions fills in the blanks
// NewOptions creates new options struct and fills it
func NewOptions(opts ...Option) Options {
var options Options
options := Options{
Client: client.DefaultClient,
Router: router.DefaultRouter,
Logger: logger.DefaultLogger,
MaxRecvSize: DefaultMaxRecvSize,
}
for _, o := range opts {
o(&options)
}
// create service if its blank
if options.Service == nil {
WithService(micro.NewService())(&options)
}
// set namespace if blank
if len(options.Namespace) == 0 {
WithNamespace("go.micro.api")(&options)
@@ -47,9 +57,16 @@ func WithRouter(r router.Router) Option {
}
}
// WithService specifies a micro.Service
func WithService(s micro.Service) Option {
// WithClient specifies client to be used by the handler
func WithClient(c client.Client) Option {
return func(o *Options) {
o.Service = s
o.Client = c
}
}
// WithMaxRecvSize specifies max body size
func WithMaxRecvSize(size int64) Option {
return func(o *Options) {
o.MaxRecvSize = size
}
}

View File

@@ -1,211 +0,0 @@
// Package registry is a go-micro/registry handler
package registry
import (
"encoding/json"
"io/ioutil"
"net/http"
"strconv"
"time"
"github.com/gorilla/websocket"
"github.com/micro/go-micro/api/handler"
"github.com/micro/go-micro/registry"
)
const (
Handler = "registry"
pingTime = (readDeadline * 9) / 10
readLimit = 16384
readDeadline = 60 * time.Second
writeDeadline = 10 * time.Second
)
type registryHandler struct {
opts handler.Options
reg registry.Registry
}
func (rh *registryHandler) add(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
b, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
defer r.Body.Close()
var opts []registry.RegisterOption
// parse ttl
if ttl := r.Form.Get("ttl"); len(ttl) > 0 {
d, err := time.ParseDuration(ttl)
if err == nil {
opts = append(opts, registry.RegisterTTL(d))
}
}
var service *registry.Service
err = json.Unmarshal(b, &service)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
err = rh.reg.Register(service, opts...)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
}
func (rh *registryHandler) del(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
b, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
defer r.Body.Close()
var service *registry.Service
err = json.Unmarshal(b, &service)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
err = rh.reg.Deregister(service)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
}
func (rh *registryHandler) get(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
service := r.Form.Get("service")
var s []*registry.Service
var err error
if len(service) == 0 {
//
upgrade := r.Header.Get("Upgrade")
connect := r.Header.Get("Connection")
// watch if websockets
if upgrade == "websocket" && connect == "Upgrade" {
rw, err := rh.reg.Watch()
if err != nil {
http.Error(w, err.Error(), 500)
return
}
watch(rw, w, r)
return
}
// otherwise list services
s, err = rh.reg.ListServices()
} else {
s, err = rh.reg.GetService(service)
}
if err != nil {
http.Error(w, err.Error(), 500)
return
}
if s == nil || (len(service) > 0 && (len(s) == 0 || len(s[0].Name) == 0)) {
http.Error(w, "Service not found", 404)
return
}
b, err := json.Marshal(s)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Length", strconv.Itoa(len(b)))
w.Write(b)
}
func ping(ws *websocket.Conn, exit chan bool) {
ticker := time.NewTicker(pingTime)
for {
select {
case <-ticker.C:
ws.SetWriteDeadline(time.Now().Add(writeDeadline))
err := ws.WriteMessage(websocket.PingMessage, []byte{})
if err != nil {
return
}
case <-exit:
return
}
}
}
func watch(rw registry.Watcher, w http.ResponseWriter, r *http.Request) {
upgrader := websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
// we need an exit chan
exit := make(chan bool)
defer func() {
close(exit)
}()
// ping the socket
go ping(ws, exit)
for {
// get next result
r, err := rw.Next()
if err != nil {
http.Error(w, err.Error(), 500)
return
}
// write to client
ws.SetWriteDeadline(time.Now().Add(writeDeadline))
if err := ws.WriteJSON(r); err != nil {
return
}
}
}
func (rh *registryHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
rh.get(w, r)
case "POST":
rh.add(w, r)
case "DELETE":
rh.del(w, r)
}
}
func (rh *registryHandler) String() string {
return "registry"
}
func NewHandler(opts ...handler.Option) handler.Handler {
options := handler.NewOptions(opts...)
return &registryHandler{
opts: options,
reg: options.Service.Client().Options().Registry,
}
}

View File

@@ -1,309 +0,0 @@
// Package rpc is a go-micro rpc handler.
package rpc
import (
"encoding/json"
"io"
"io/ioutil"
"net/http"
"strconv"
"strings"
"github.com/joncalhoun/qson"
"github.com/micro/go-micro/api"
"github.com/micro/go-micro/api/handler"
proto "github.com/micro/go-micro/api/internal/proto"
"github.com/micro/go-micro/client"
"github.com/micro/go-micro/client/selector"
"github.com/micro/go-micro/codec"
"github.com/micro/go-micro/codec/jsonrpc"
"github.com/micro/go-micro/codec/protorpc"
"github.com/micro/go-micro/errors"
"github.com/micro/go-micro/registry"
"github.com/micro/go-micro/util/ctx"
)
const (
Handler = "rpc"
)
var (
// supported json codecs
jsonCodecs = []string{
"application/grpc+json",
"application/json",
"application/json-rpc",
}
// support proto codecs
protoCodecs = []string{
"application/grpc",
"application/grpc+proto",
"application/proto",
"application/protobuf",
"application/proto-rpc",
"application/octet-stream",
}
)
type rpcHandler struct {
opts handler.Options
s *api.Service
}
type buffer struct {
io.ReadCloser
}
func (b *buffer) Write(_ []byte) (int, error) {
return 0, nil
}
// strategy is a hack for selection
func strategy(services []*registry.Service) selector.Strategy {
return func(_ []*registry.Service) selector.Next {
// ignore input to this function, use services above
return selector.Random(services)
}
}
func (h *rpcHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
var service *api.Service
if h.s != nil {
// we were given the service
service = h.s
} else if h.opts.Router != nil {
// try get service from router
s, err := h.opts.Router.Route(r)
if err != nil {
writeError(w, r, errors.InternalServerError("go.micro.api", err.Error()))
return
}
service = s
} else {
// we have no way of routing the request
writeError(w, r, errors.InternalServerError("go.micro.api", "no route found"))
return
}
// only allow post when we have the router
if r.Method != "GET" && (h.opts.Router != nil && r.Method != "POST") {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
ct := r.Header.Get("Content-Type")
// Strip charset from Content-Type (like `application/json; charset=UTF-8`)
if idx := strings.IndexRune(ct, ';'); idx >= 0 {
ct = ct[:idx]
}
// micro client
c := h.opts.Service.Client()
// create strategy
so := selector.WithStrategy(strategy(service.Services))
// get payload
br, err := requestPayload(r)
if err != nil {
writeError(w, r, err)
return
}
// create context
cx := ctx.FromRequest(r)
var rsp []byte
switch {
// proto codecs
case hasCodec(ct, protoCodecs):
request := &proto.Message{}
// if the extracted payload isn't empty lets use it
if len(br) > 0 {
request = proto.NewMessage(br)
}
// create request/response
response := &proto.Message{}
req := c.NewRequest(
service.Name,
service.Endpoint.Name,
request,
client.WithContentType(ct),
)
// make the call
if err := c.Call(cx, req, response, client.WithSelectOption(so)); err != nil {
writeError(w, r, err)
return
}
// marshall response
rsp, _ = response.Marshal()
default:
// if json codec is not present set to json
if !hasCodec(ct, jsonCodecs) {
ct = "application/json"
}
// default to trying json
var request json.RawMessage
// if the extracted payload isn't empty lets use it
if len(br) > 0 {
request = json.RawMessage(br)
}
// create request/response
var response json.RawMessage
req := c.NewRequest(
service.Name,
service.Endpoint.Name,
&request,
client.WithContentType(ct),
)
// make the call
if err := c.Call(cx, req, &response, client.WithSelectOption(so)); err != nil {
writeError(w, r, err)
return
}
// marshall response
rsp, _ = response.MarshalJSON()
}
// write the response
writeResponse(w, r, rsp)
}
func (rh *rpcHandler) String() string {
return "rpc"
}
func hasCodec(ct string, codecs []string) bool {
for _, codec := range codecs {
if ct == codec {
return true
}
}
return false
}
// requestPayload takes a *http.Request.
// If the request is a GET the query string parameters are extracted and marshaled to JSON and the raw bytes are returned.
// If the request method is a POST the request body is read and returned
func requestPayload(r *http.Request) ([]byte, error) {
// we have to decode json-rpc and proto-rpc because we suck
// well actually because there's no proxy codec right now
switch r.Header.Get("Content-Type") {
case "application/json-rpc":
msg := codec.Message{
Type: codec.Request,
Header: make(map[string]string),
}
c := jsonrpc.NewCodec(&buffer{r.Body})
if err := c.ReadHeader(&msg, codec.Request); err != nil {
return nil, err
}
var raw json.RawMessage
if err := c.ReadBody(&raw); err != nil {
return nil, err
}
return ([]byte)(raw), nil
case "application/proto-rpc", "application/octet-stream":
msg := codec.Message{
Type: codec.Request,
Header: make(map[string]string),
}
c := protorpc.NewCodec(&buffer{r.Body})
if err := c.ReadHeader(&msg, codec.Request); err != nil {
return nil, err
}
var raw proto.Message
if err := c.ReadBody(&raw); err != nil {
return nil, err
}
b, _ := raw.Marshal()
return b, nil
}
// otherwise as per usual
switch r.Method {
case "GET":
if len(r.URL.RawQuery) > 0 {
return qson.ToJSON(r.URL.RawQuery)
}
case "PATCH", "POST":
return ioutil.ReadAll(r.Body)
}
return []byte{}, nil
}
func writeError(w http.ResponseWriter, r *http.Request, err error) {
ce := errors.Parse(err.Error())
switch ce.Code {
case 0:
// assuming it's totally screwed
ce.Code = 500
ce.Id = "go.micro.api"
ce.Status = http.StatusText(500)
ce.Detail = "error during request: " + ce.Detail
w.WriteHeader(500)
default:
w.WriteHeader(int(ce.Code))
}
// response content type
w.Header().Set("Content-Type", "application/json")
// Set trailers
if strings.Contains(r.Header.Get("Content-Type"), "application/grpc") {
w.Header().Set("Trailer", "grpc-status")
w.Header().Set("Trailer", "grpc-message")
w.Header().Set("grpc-status", "13")
w.Header().Set("grpc-message", ce.Detail)
}
w.Write([]byte(ce.Error()))
}
func writeResponse(w http.ResponseWriter, r *http.Request, rsp []byte) {
w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
w.Header().Set("Content-Length", strconv.Itoa(len(rsp)))
// Set trailers
if strings.Contains(r.Header.Get("Content-Type"), "application/grpc") {
w.Header().Set("Trailer", "grpc-status")
w.Header().Set("Trailer", "grpc-message")
w.Header().Set("grpc-status", "0")
w.Header().Set("grpc-message", "")
}
// write response
w.Write(rsp)
}
func NewHandler(opts ...handler.Option) handler.Handler {
options := handler.NewOptions(opts...)
return &rpcHandler{
opts: options,
}
}
func WithService(s *api.Service, opts ...handler.Option) handler.Handler {
options := handler.NewOptions(opts...)
return &rpcHandler{
opts: options,
s: s,
}
}

View File

@@ -1,95 +0,0 @@
package rpc
import (
"bytes"
"encoding/json"
"net/http"
"testing"
"github.com/golang/protobuf/proto"
"github.com/micro/go-micro/api/proto"
)
func TestRequestPayloadFromRequest(t *testing.T) {
// our test event so that we can validate serialising / deserializing of true protos works
protoEvent := go_api.Event{
Name: "Test",
}
protoBytes, err := proto.Marshal(&protoEvent)
if err != nil {
t.Fatal("Failed to marshal proto", err)
}
jsonBytes, err := json.Marshal(protoEvent)
if err != nil {
t.Fatal("Failed to marshal proto to JSON ", err)
}
t.Run("extracting a proto from a POST request", func(t *testing.T) {
r, err := http.NewRequest("POST", "http://localhost/my/path", bytes.NewReader(protoBytes))
if err != nil {
t.Fatalf("Failed to created http.Request: %v", err)
}
extByte, err := requestPayload(r)
if err != nil {
t.Fatalf("Failed to extract payload from request: %v", err)
}
if string(extByte) != string(protoBytes) {
t.Fatalf("Expected %v and %v to match", string(extByte), string(protoBytes))
}
})
t.Run("extracting JSON from a POST request", func(t *testing.T) {
r, err := http.NewRequest("POST", "http://localhost/my/path", bytes.NewReader(jsonBytes))
if err != nil {
t.Fatalf("Failed to created http.Request: %v", err)
}
extByte, err := requestPayload(r)
if err != nil {
t.Fatalf("Failed to extract payload from request: %v", err)
}
if string(extByte) != string(jsonBytes) {
t.Fatalf("Expected %v and %v to match", string(extByte), string(jsonBytes))
}
})
t.Run("extracting params from a GET request", func(t *testing.T) {
r, err := http.NewRequest("GET", "http://localhost/my/path", nil)
if err != nil {
t.Fatalf("Failed to created http.Request: %v", err)
}
q := r.URL.Query()
q.Add("name", "Test")
r.URL.RawQuery = q.Encode()
extByte, err := requestPayload(r)
if err != nil {
t.Fatalf("Failed to extract payload from request: %v", err)
}
if string(extByte) != string(jsonBytes) {
t.Fatalf("Expected %v and %v to match", string(extByte), string(jsonBytes))
}
})
t.Run("GET request with no params", func(t *testing.T) {
r, err := http.NewRequest("GET", "http://localhost/my/path", nil)
if err != nil {
t.Fatalf("Failed to created http.Request: %v", err)
}
extByte, err := requestPayload(r)
if err != nil {
t.Fatalf("Failed to extract payload from request: %v", err)
}
if string(extByte) != "" {
t.Fatalf("Expected %v and %v to match", string(extByte), "")
}
})
}

View File

@@ -1,25 +0,0 @@
// Package udp reads and write from a udp connection
package udp
import (
"io"
"net"
"net/http"
)
type Handler struct{}
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
c, err := net.Dial("udp", r.Host)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
go io.Copy(c, r.Body)
// write response
io.Copy(w, c)
}
func (h *Handler) String() string {
return "udp"
}

View File

@@ -1,30 +0,0 @@
// Package unix reads from a unix socket expecting it to be in /tmp/path
package unix
import (
"fmt"
"io"
"net"
"net/http"
"path/filepath"
)
type Handler struct{}
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
sock := fmt.Sprintf("%s.sock", filepath.Clean(r.URL.Path))
path := filepath.Join("/tmp", sock)
c, err := net.Dial("unix", path)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
go io.Copy(c, r.Body)
// write response
io.Copy(w, c)
}
func (h *Handler) String() string {
return "unix"
}

View File

@@ -1,177 +0,0 @@
// Package web contains the web handler including websocket support
package web
import (
"errors"
"fmt"
"io"
"net"
"net/http"
"net/http/httputil"
"net/url"
"strings"
"github.com/micro/go-micro/api"
"github.com/micro/go-micro/api/handler"
"github.com/micro/go-micro/client/selector"
)
const (
Handler = "web"
)
type webHandler struct {
opts handler.Options
s *api.Service
}
func (wh *webHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
service, err := wh.getService(r)
if err != nil {
w.WriteHeader(500)
return
}
if len(service) == 0 {
w.WriteHeader(404)
return
}
rp, err := url.Parse(service)
if err != nil {
w.WriteHeader(500)
return
}
if isWebSocket(r) {
wh.serveWebSocket(rp.Host, w, r)
return
}
httputil.NewSingleHostReverseProxy(rp).ServeHTTP(w, r)
}
// getService returns the service for this request from the selector
func (wh *webHandler) getService(r *http.Request) (string, error) {
var service *api.Service
if wh.s != nil {
// we were given the service
service = wh.s
} else if wh.opts.Router != nil {
// try get service from router
s, err := wh.opts.Router.Route(r)
if err != nil {
return "", err
}
service = s
} else {
// we have no way of routing the request
return "", errors.New("no route found")
}
// create a random selector
next := selector.Random(service.Services)
// get the next node
s, err := next()
if err != nil {
return "", nil
}
return fmt.Sprintf("http://%s", s.Address), nil
}
// serveWebSocket used to serve a web socket proxied connection
func (wh *webHandler) serveWebSocket(host string, w http.ResponseWriter, r *http.Request) {
req := new(http.Request)
*req = *r
if len(host) == 0 {
http.Error(w, "invalid host", 500)
return
}
// set x-forward-for
if clientIP, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
if ips, ok := req.Header["X-Forwarded-For"]; ok {
clientIP = strings.Join(ips, ", ") + ", " + clientIP
}
req.Header.Set("X-Forwarded-For", clientIP)
}
// connect to the backend host
conn, err := net.Dial("tcp", host)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
// hijack the connection
hj, ok := w.(http.Hijacker)
if !ok {
http.Error(w, "failed to connect", 500)
return
}
nc, _, err := hj.Hijack()
if err != nil {
return
}
defer nc.Close()
defer conn.Close()
if err = req.Write(conn); err != nil {
return
}
errCh := make(chan error, 2)
cp := func(dst io.Writer, src io.Reader) {
_, err := io.Copy(dst, src)
errCh <- err
}
go cp(conn, nc)
go cp(nc, conn)
<-errCh
}
func isWebSocket(r *http.Request) bool {
contains := func(key, val string) bool {
vv := strings.Split(r.Header.Get(key), ",")
for _, v := range vv {
if val == strings.ToLower(strings.TrimSpace(v)) {
return true
}
}
return false
}
if contains("Connection", "upgrade") && contains("Upgrade", "websocket") {
return true
}
return false
}
func (wh *webHandler) String() string {
return "web"
}
func NewHandler(opts ...handler.Option) handler.Handler {
return &webHandler{
opts: handler.NewOptions(opts...),
}
}
func WithService(s *api.Service, opts ...handler.Option) handler.Handler {
options := handler.NewOptions(opts...)
return &webHandler{
opts: options,
s: s,
}
}

View File

@@ -1,28 +0,0 @@
package proto
type Message struct {
data []byte
}
func (m *Message) ProtoMessage() {}
func (m *Message) Reset() {
*m = Message{}
}
func (m *Message) String() string {
return string(m.data)
}
func (m *Message) Marshal() ([]byte, error) {
return m.data, nil
}
func (m *Message) Unmarshal(data []byte) error {
m.data = data
return nil
}
func NewMessage(data []byte) *Message {
return &Message{data}
}

View File

@@ -1,31 +0,0 @@
// Code generated by protoc-gen-micro. DO NOT EDIT.
// source: github.com/micro/go-micro/api/proto/api.proto
/*
Package go_api is a generated protocol buffer package.
It is generated from these files:
github.com/micro/go-micro/api/proto/api.proto
It has these top-level messages:
Pair
Request
Response
Event
*/
package go_api
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
// 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

View File

@@ -1,332 +0,0 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: github.com/micro/go-micro/api/proto/api.proto
package go_api
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
// 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 Pair struct {
Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"`
Values []string `protobuf:"bytes,2,rep,name=values,proto3" json:"values,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *Pair) Reset() { *m = Pair{} }
func (m *Pair) String() string { return proto.CompactTextString(m) }
func (*Pair) ProtoMessage() {}
func (*Pair) Descriptor() ([]byte, []int) {
return fileDescriptor_api_17a7876430d97ebd, []int{0}
}
func (m *Pair) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_Pair.Unmarshal(m, b)
}
func (m *Pair) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_Pair.Marshal(b, m, deterministic)
}
func (dst *Pair) XXX_Merge(src proto.Message) {
xxx_messageInfo_Pair.Merge(dst, src)
}
func (m *Pair) XXX_Size() int {
return xxx_messageInfo_Pair.Size(m)
}
func (m *Pair) XXX_DiscardUnknown() {
xxx_messageInfo_Pair.DiscardUnknown(m)
}
var xxx_messageInfo_Pair proto.InternalMessageInfo
func (m *Pair) GetKey() string {
if m != nil {
return m.Key
}
return ""
}
func (m *Pair) GetValues() []string {
if m != nil {
return m.Values
}
return nil
}
// A HTTP request as RPC
// Forward by the api handler
type Request struct {
Method string `protobuf:"bytes,1,opt,name=method,proto3" json:"method,omitempty"`
Path string `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"`
Header map[string]*Pair `protobuf:"bytes,3,rep,name=header,proto3" json:"header,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
Get map[string]*Pair `protobuf:"bytes,4,rep,name=get,proto3" json:"get,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
Post map[string]*Pair `protobuf:"bytes,5,rep,name=post,proto3" json:"post,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
Body string `protobuf:"bytes,6,opt,name=body,proto3" json:"body,omitempty"`
Url string `protobuf:"bytes,7,opt,name=url,proto3" json:"url,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *Request) Reset() { *m = Request{} }
func (m *Request) String() string { return proto.CompactTextString(m) }
func (*Request) ProtoMessage() {}
func (*Request) Descriptor() ([]byte, []int) {
return fileDescriptor_api_17a7876430d97ebd, []int{1}
}
func (m *Request) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_Request.Unmarshal(m, b)
}
func (m *Request) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_Request.Marshal(b, m, deterministic)
}
func (dst *Request) XXX_Merge(src proto.Message) {
xxx_messageInfo_Request.Merge(dst, src)
}
func (m *Request) XXX_Size() int {
return xxx_messageInfo_Request.Size(m)
}
func (m *Request) XXX_DiscardUnknown() {
xxx_messageInfo_Request.DiscardUnknown(m)
}
var xxx_messageInfo_Request proto.InternalMessageInfo
func (m *Request) GetMethod() string {
if m != nil {
return m.Method
}
return ""
}
func (m *Request) GetPath() string {
if m != nil {
return m.Path
}
return ""
}
func (m *Request) GetHeader() map[string]*Pair {
if m != nil {
return m.Header
}
return nil
}
func (m *Request) GetGet() map[string]*Pair {
if m != nil {
return m.Get
}
return nil
}
func (m *Request) GetPost() map[string]*Pair {
if m != nil {
return m.Post
}
return nil
}
func (m *Request) GetBody() string {
if m != nil {
return m.Body
}
return ""
}
func (m *Request) GetUrl() string {
if m != nil {
return m.Url
}
return ""
}
// A HTTP response as RPC
// Expected response for the api handler
type Response struct {
StatusCode int32 `protobuf:"varint,1,opt,name=statusCode,proto3" json:"statusCode,omitempty"`
Header map[string]*Pair `protobuf:"bytes,2,rep,name=header,proto3" json:"header,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
Body string `protobuf:"bytes,3,opt,name=body,proto3" json:"body,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *Response) Reset() { *m = Response{} }
func (m *Response) String() string { return proto.CompactTextString(m) }
func (*Response) ProtoMessage() {}
func (*Response) Descriptor() ([]byte, []int) {
return fileDescriptor_api_17a7876430d97ebd, []int{2}
}
func (m *Response) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_Response.Unmarshal(m, b)
}
func (m *Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_Response.Marshal(b, m, deterministic)
}
func (dst *Response) XXX_Merge(src proto.Message) {
xxx_messageInfo_Response.Merge(dst, src)
}
func (m *Response) XXX_Size() int {
return xxx_messageInfo_Response.Size(m)
}
func (m *Response) XXX_DiscardUnknown() {
xxx_messageInfo_Response.DiscardUnknown(m)
}
var xxx_messageInfo_Response proto.InternalMessageInfo
func (m *Response) GetStatusCode() int32 {
if m != nil {
return m.StatusCode
}
return 0
}
func (m *Response) GetHeader() map[string]*Pair {
if m != nil {
return m.Header
}
return nil
}
func (m *Response) GetBody() string {
if m != nil {
return m.Body
}
return ""
}
// A HTTP event as RPC
// Forwarded by the event handler
type Event struct {
// e.g login
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
// uuid
Id string `protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"`
// unix timestamp of event
Timestamp int64 `protobuf:"varint,3,opt,name=timestamp,proto3" json:"timestamp,omitempty"`
// event headers
Header map[string]*Pair `protobuf:"bytes,4,rep,name=header,proto3" json:"header,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
// the event data
Data string `protobuf:"bytes,5,opt,name=data,proto3" json:"data,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *Event) Reset() { *m = Event{} }
func (m *Event) String() string { return proto.CompactTextString(m) }
func (*Event) ProtoMessage() {}
func (*Event) Descriptor() ([]byte, []int) {
return fileDescriptor_api_17a7876430d97ebd, []int{3}
}
func (m *Event) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_Event.Unmarshal(m, b)
}
func (m *Event) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_Event.Marshal(b, m, deterministic)
}
func (dst *Event) XXX_Merge(src proto.Message) {
xxx_messageInfo_Event.Merge(dst, src)
}
func (m *Event) XXX_Size() int {
return xxx_messageInfo_Event.Size(m)
}
func (m *Event) XXX_DiscardUnknown() {
xxx_messageInfo_Event.DiscardUnknown(m)
}
var xxx_messageInfo_Event proto.InternalMessageInfo
func (m *Event) GetName() string {
if m != nil {
return m.Name
}
return ""
}
func (m *Event) GetId() string {
if m != nil {
return m.Id
}
return ""
}
func (m *Event) GetTimestamp() int64 {
if m != nil {
return m.Timestamp
}
return 0
}
func (m *Event) GetHeader() map[string]*Pair {
if m != nil {
return m.Header
}
return nil
}
func (m *Event) GetData() string {
if m != nil {
return m.Data
}
return ""
}
func init() {
proto.RegisterType((*Pair)(nil), "go.api.Pair")
proto.RegisterType((*Request)(nil), "go.api.Request")
proto.RegisterMapType((map[string]*Pair)(nil), "go.api.Request.GetEntry")
proto.RegisterMapType((map[string]*Pair)(nil), "go.api.Request.HeaderEntry")
proto.RegisterMapType((map[string]*Pair)(nil), "go.api.Request.PostEntry")
proto.RegisterType((*Response)(nil), "go.api.Response")
proto.RegisterMapType((map[string]*Pair)(nil), "go.api.Response.HeaderEntry")
proto.RegisterType((*Event)(nil), "go.api.Event")
proto.RegisterMapType((map[string]*Pair)(nil), "go.api.Event.HeaderEntry")
}
func init() {
proto.RegisterFile("github.com/micro/go-micro/api/proto/api.proto", fileDescriptor_api_17a7876430d97ebd)
}
var fileDescriptor_api_17a7876430d97ebd = []byte{
// 410 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x53, 0xc1, 0x6e, 0xd4, 0x30,
0x10, 0x55, 0xe2, 0x24, 0x6d, 0x66, 0x11, 0x42, 0x3e, 0x20, 0x53, 0x2a, 0xb4, 0xca, 0x85, 0x15,
0x52, 0x13, 0x68, 0x39, 0x20, 0xae, 0xb0, 0x2a, 0xc7, 0xca, 0x7f, 0xe0, 0x6d, 0xac, 0xc4, 0x62,
0x13, 0x9b, 0xd8, 0xa9, 0xb4, 0x1f, 0xc7, 0x81, 0xcf, 0xe0, 0x6f, 0x90, 0x27, 0xde, 0xdd, 0xb2,
0x5a, 0x2e, 0x74, 0x6f, 0x2f, 0xf6, 0x9b, 0x37, 0x6f, 0xde, 0x38, 0xf0, 0xb6, 0x51, 0xae, 0x1d,
0x57, 0xe5, 0xbd, 0xee, 0xaa, 0x4e, 0xdd, 0x0f, 0xba, 0x6a, 0xf4, 0x95, 0x30, 0xaa, 0x32, 0x83,
0x76, 0xba, 0x12, 0x46, 0x95, 0x88, 0x68, 0xd6, 0xe8, 0x52, 0x18, 0x55, 0xbc, 0x87, 0xe4, 0x4e,
0xa8, 0x81, 0xbe, 0x00, 0xf2, 0x5d, 0x6e, 0x58, 0x34, 0x8f, 0x16, 0x39, 0xf7, 0x90, 0xbe, 0x84,
0xec, 0x41, 0xac, 0x47, 0x69, 0x59, 0x3c, 0x27, 0x8b, 0x9c, 0x87, 0xaf, 0xe2, 0x17, 0x81, 0x33,
0x2e, 0x7f, 0x8c, 0xd2, 0x3a, 0xcf, 0xe9, 0xa4, 0x6b, 0x75, 0x1d, 0x0a, 0xc3, 0x17, 0xa5, 0x90,
0x18, 0xe1, 0x5a, 0x16, 0xe3, 0x29, 0x62, 0x7a, 0x03, 0x59, 0x2b, 0x45, 0x2d, 0x07, 0x46, 0xe6,
0x64, 0x31, 0xbb, 0x7e, 0x5d, 0x4e, 0x16, 0xca, 0x20, 0x56, 0x7e, 0xc3, 0xdb, 0x65, 0xef, 0x86,
0x0d, 0x0f, 0x54, 0xfa, 0x0e, 0x48, 0x23, 0x1d, 0x4b, 0xb0, 0x82, 0x1d, 0x56, 0xdc, 0x4a, 0x37,
0xd1, 0x3d, 0x89, 0x5e, 0x41, 0x62, 0xb4, 0x75, 0x2c, 0x45, 0xf2, 0xab, 0x43, 0xf2, 0x9d, 0xb6,
0x81, 0x8d, 0x34, 0xef, 0x71, 0xa5, 0xeb, 0x0d, 0xcb, 0x26, 0x8f, 0x1e, 0xfb, 0x14, 0xc6, 0x61,
0xcd, 0xce, 0xa6, 0x14, 0xc6, 0x61, 0x7d, 0x71, 0x0b, 0xb3, 0x47, 0xbe, 0x8e, 0xc4, 0x54, 0x40,
0x8a, 0xc1, 0xe0, 0xac, 0xb3, 0xeb, 0x67, 0xdb, 0xb6, 0x3e, 0x55, 0x3e, 0x5d, 0x7d, 0x8e, 0x3f,
0x45, 0x17, 0x5f, 0xe1, 0x7c, 0x6b, 0xf7, 0x09, 0x2a, 0x4b, 0xc8, 0x77, 0x73, 0xfc, 0xbf, 0x4c,
0xf1, 0x33, 0x82, 0x73, 0x2e, 0xad, 0xd1, 0xbd, 0x95, 0xf4, 0x0d, 0x80, 0x75, 0xc2, 0x8d, 0xf6,
0x8b, 0xae, 0x25, 0xaa, 0xa5, 0xfc, 0xd1, 0x09, 0xfd, 0xb8, 0x5b, 0x5c, 0x8c, 0xc9, 0x5e, 0xee,
0x93, 0x9d, 0x14, 0x8e, 0x6e, 0x6e, 0x1b, 0x2f, 0xd9, 0xc7, 0x7b, 0xb2, 0x30, 0x8b, 0xdf, 0x11,
0xa4, 0xcb, 0x07, 0xd9, 0xe3, 0x16, 0x7b, 0xd1, 0xc9, 0x20, 0x82, 0x98, 0x3e, 0x87, 0x58, 0xd5,
0xe1, 0xed, 0xc5, 0xaa, 0xa6, 0x97, 0x90, 0x3b, 0xd5, 0x49, 0xeb, 0x44, 0x67, 0xd0, 0x0f, 0xe1,
0xfb, 0x03, 0xfa, 0x61, 0x37, 0x5e, 0xf2, 0xf7, 0xc3, 0xc1, 0x06, 0xff, 0x9a, 0xad, 0x16, 0x4e,
0xb0, 0x74, 0x6a, 0xea, 0xf1, 0xc9, 0x66, 0x5b, 0x65, 0xf8, 0x83, 0xde, 0xfc, 0x09, 0x00, 0x00,
0xff, 0xff, 0x7a, 0xb4, 0xd4, 0x8f, 0xcb, 0x03, 0x00, 0x00,
}

View File

@@ -1,43 +0,0 @@
syntax = "proto3";
package go.api;
message Pair {
string key = 1;
repeated string values = 2;
}
// A HTTP request as RPC
// Forward by the api handler
message Request {
string method = 1;
string path = 2;
map<string, Pair> header = 3;
map<string, Pair> get = 4;
map<string, Pair> post = 5;
string body = 6; // raw request body; if not application/x-www-form-urlencoded
string url = 7;
}
// A HTTP response as RPC
// Expected response for the api handler
message Response {
int32 statusCode = 1;
map<string, Pair> header = 2;
string body = 3;
}
// A HTTP event as RPC
// Forwarded by the event handler
message Event {
// e.g login
string name = 1;
// uuid
string id = 2;
// unix timestamp of event
int64 timestamp = 3;
// event headers
map<string, Pair> header = 4;
// the event data
string data = 5;
}

View File

@@ -6,12 +6,19 @@ import (
"net/http"
"strings"
"github.com/micro/go-micro/api/resolver"
"github.com/unistack-org/micro/v3/api/resolver"
)
type Resolver struct{}
// Resolver struct
type Resolver struct {
opts resolver.Options
}
// Resolve func to resolve enndpoint
func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) {
// parse options
options := resolver.NewResolveOptions(opts...)
func (r *Resolver) Resolve(req *http.Request) (*resolver.Endpoint, error) {
// /foo.Bar/Service
if req.URL.Path == "/" {
return nil, errors.New("unknown name")
@@ -26,6 +33,7 @@ func (r *Resolver) Resolve(req *http.Request) (*resolver.Endpoint, error) {
Host: req.Host,
Method: req.Method,
Path: req.URL.Path,
Domain: options.Domain,
}, nil
}
@@ -33,6 +41,7 @@ func (r *Resolver) String() string {
return "grpc"
}
// NewResolver is used to create new Resolver
func NewResolver(opts ...resolver.Option) resolver.Resolver {
return &Resolver{}
return &Resolver{opts: resolver.NewOptions(opts...)}
}

View File

@@ -4,24 +4,32 @@ package host
import (
"net/http"
"github.com/micro/go-micro/api/resolver"
"github.com/unistack-org/micro/v3/api/resolver"
)
type Resolver struct{}
type hostResolver struct {
opts resolver.Options
}
// Resolve endpoint
func (r *hostResolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) {
// parse options
options := resolver.NewResolveOptions(opts...)
func (r *Resolver) Resolve(req *http.Request) (*resolver.Endpoint, error) {
return &resolver.Endpoint{
Name: req.Host,
Host: req.Host,
Method: req.Method,
Path: req.URL.Path,
Domain: options.Domain,
}, nil
}
func (r *Resolver) String() string {
func (r *hostResolver) String() string {
return "host"
}
// NewResolver creates new host api resolver
func NewResolver(opts ...resolver.Option) resolver.Resolver {
return &Resolver{}
return &hostResolver{opts: resolver.NewOptions(opts...)}
}

View File

@@ -1,45 +0,0 @@
// Package micro provides a micro rpc resolver which prefixes a namespace
package micro
import (
"net/http"
"github.com/micro/go-micro/api/resolver"
)
// default resolver for legacy purposes
// it uses proxy routing to resolve names
// /foo becomes namespace.foo
// /v1/foo becomes namespace.v1.foo
type Resolver struct {
Options resolver.Options
}
func (r *Resolver) Resolve(req *http.Request) (*resolver.Endpoint, error) {
var name, method string
switch r.Options.Handler {
// internal handlers
case "meta", "api", "rpc", "micro":
name, method = apiRoute(req.URL.Path)
default:
method = req.Method
name = proxyRoute(req.URL.Path)
}
return &resolver.Endpoint{
Name: name,
Method: method,
}, nil
}
func (r *Resolver) String() string {
return "micro"
}
// NewResolver creates a new micro resolver
func NewResolver(opts ...resolver.Option) resolver.Resolver {
return &Resolver{
Options: resolver.NewOptions(opts...),
}
}

View File

@@ -1,90 +0,0 @@
package micro
import (
"path"
"regexp"
"strings"
)
var (
proxyRe = regexp.MustCompile("^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$")
versionRe = regexp.MustCompilePOSIX("^v[0-9]+$")
)
// Translates /foo/bar/zool into api service go.micro.api.foo method Bar.Zool
// Translates /foo/bar into api service go.micro.api.foo method Foo.Bar
func apiRoute(p string) (string, string) {
p = path.Clean(p)
p = strings.TrimPrefix(p, "/")
parts := strings.Split(p, "/")
// If we've got two or less parts
// Use first part as service
// Use all parts as method
if len(parts) <= 2 {
name := parts[0]
return name, methodName(parts)
}
// Treat /v[0-9]+ as versioning where we have 3 parts
// /v1/foo/bar => service: v1.foo method: Foo.bar
if len(parts) == 3 && versionRe.Match([]byte(parts[0])) {
name := strings.Join(parts[:len(parts)-1], ".")
return name, methodName(parts[len(parts)-2:])
}
// Service is everything minus last two parts
// Method is the last two parts
name := strings.Join(parts[:len(parts)-2], ".")
return name, methodName(parts[len(parts)-2:])
}
func proxyRoute(p string) string {
parts := strings.Split(p, "/")
if len(parts) < 2 {
return ""
}
var service string
var alias string
// /[service]/methods
if len(parts) > 2 {
// /v1/[service]
if versionRe.MatchString(parts[1]) {
service = parts[1] + "." + parts[2]
alias = parts[2]
} else {
service = parts[1]
alias = parts[1]
}
// /[service]
} else {
service = parts[1]
alias = parts[1]
}
// check service name is valid
if !proxyRe.MatchString(alias) {
return ""
}
return service
}
func methodName(parts []string) string {
for i, part := range parts {
parts[i] = toCamel(part)
}
return strings.Join(parts, ".")
}
func toCamel(s string) string {
words := strings.Split(s, "-")
var out string
for _, word := range words {
out += strings.Title(word)
}
return out
}

View File

@@ -1,130 +0,0 @@
package micro
import (
"testing"
)
func TestApiRoute(t *testing.T) {
testData := []struct {
path string
service string
method string
}{
{
"/foo/bar",
"foo",
"Foo.Bar",
},
{
"/foo/foo/bar",
"foo",
"Foo.Bar",
},
{
"/foo/bar/baz",
"foo",
"Bar.Baz",
},
{
"/foo/bar/baz-xyz",
"foo",
"Bar.BazXyz",
},
{
"/foo/bar/baz/cat",
"foo.bar",
"Baz.Cat",
},
{
"/foo/bar/baz/cat/car",
"foo.bar.baz",
"Cat.Car",
},
{
"/foo/fooBar/bazCat",
"foo",
"FooBar.BazCat",
},
{
"/v1/foo/bar",
"v1.foo",
"Foo.Bar",
},
{
"/v1/foo/bar/baz",
"v1.foo",
"Bar.Baz",
},
{
"/v1/foo/bar/baz/cat",
"v1.foo.bar",
"Baz.Cat",
},
}
for _, d := range testData {
s, m := apiRoute(d.path)
if d.service != s {
t.Fatalf("Expected service: %s for path: %s got: %s %s", d.service, d.path, s, m)
}
if d.method != m {
t.Fatalf("Expected service: %s for path: %s got: %s", d.method, d.path, m)
}
}
}
func TestProxyRoute(t *testing.T) {
testData := []struct {
path string
service string
}{
// no namespace
{
"/f",
"f",
},
{
"/f",
"f",
},
{
"/f-b",
"f-b",
},
{
"/foo/bar",
"foo",
},
{
"/foo-bar",
"foo-bar",
},
{
"/foo-bar-baz",
"foo-bar-baz",
},
{
"/foo/bar/bar",
"foo",
},
{
"/v1/foo/bar",
"v1.foo",
},
{
"/v1/foo/bar/baz",
"v1.foo",
},
{
"/v1/foo/bar/baz/cat",
"v1.foo",
},
}
for _, d := range testData {
s := proxyRoute(d.path)
if d.service != s {
t.Fatalf("Expected service: %s for path: %s got: %s", d.service, d.path, s)
}
}
}

View File

@@ -1,14 +1,24 @@
package resolver
// NewOptions returns new initialised options
func NewOptions(opts ...Option) Options {
var options Options
for _, o := range opts {
o(&options)
}
return options
import (
"context"
"github.com/unistack-org/micro/v3/register"
)
// Options struct
type Options struct {
// Context is for external defined options
Context context.Context
// Handler name
Handler string
// ServicePrefix is the prefix
ServicePrefix string
}
// Option func
type Option func(o *Options)
// WithHandler sets the handler being used
func WithHandler(h string) Option {
return func(o *Options) {
@@ -16,9 +26,45 @@ func WithHandler(h string) Option {
}
}
// WithNamespace sets the namespace being used
func WithNamespace(n string) Option {
// WithServicePrefix sets the ServicePrefix option
func WithServicePrefix(p string) Option {
return func(o *Options) {
o.Namespace = n
o.ServicePrefix = p
}
}
// NewOptions returns new initialised options
func NewOptions(opts ...Option) Options {
options := Options{
Context: context.Background(),
}
for _, o := range opts {
o(&options)
}
return options
}
// ResolveOptions are used when resolving a request
type ResolveOptions struct {
Domain string
}
// ResolveOption sets an option
type ResolveOption func(*ResolveOptions)
// Domain sets the resolve Domain option
func Domain(n string) ResolveOption {
return func(o *ResolveOptions) {
o.Domain = n
}
}
// NewResolveOptions returns new initialised resolve options
func NewResolveOptions(opts ...ResolveOption) ResolveOptions {
options := ResolveOptions{Domain: register.DefaultDomain}
for _, o := range opts {
o(&options)
}
return options
}

View File

@@ -2,32 +2,43 @@
package path
import (
"errors"
"net/http"
"strings"
"github.com/micro/go-micro/api/resolver"
"github.com/unistack-org/micro/v3/api/resolver"
)
type Resolver struct{}
// Resolver the path resolver
type Resolver struct {
opts resolver.Options
}
// Resolve resolves endpoint
func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) {
// parse options
options := resolver.NewResolveOptions(opts...)
func (r *Resolver) Resolve(req *http.Request) (*resolver.Endpoint, error) {
if req.URL.Path == "/" {
return nil, errors.New("unknown name")
return nil, resolver.ErrNotFound
}
parts := strings.Split(req.URL.Path[1:], "/")
return &resolver.Endpoint{
Name: parts[0],
Name: r.opts.ServicePrefix + "." + parts[0],
Host: req.Host,
Method: req.Method,
Path: req.URL.Path,
Domain: options.Domain,
}, nil
}
// String retruns the string representation
func (r *Resolver) String() string {
return "path"
}
// NewResolver returns new path resolver
func NewResolver(opts ...resolver.Option) resolver.Resolver {
return &Resolver{}
return &Resolver{opts: resolver.NewOptions(opts...)}
}

View File

@@ -2,18 +2,26 @@
package resolver
import (
"errors"
"net/http"
)
var (
// ErrNotFound returned when endpoint is not found
ErrNotFound = errors.New("not found")
// ErrInvalidPath returned on invalid path
ErrInvalidPath = errors.New("invalid path")
)
// Resolver resolves requests to endpoints
type Resolver interface {
Resolve(r *http.Request) (*Endpoint, error)
Resolve(r *http.Request, opts ...ResolveOption) (*Endpoint, error)
String() string
}
// Endpoint is the endpoint for a http request
type Endpoint struct {
// e.g greeter
// Endpoint name e.g greeter
Name string
// HTTP Host e.g example.com
Host string
@@ -21,11 +29,6 @@ type Endpoint struct {
Method string
// HTTP Path e.g /greeter.
Path string
// Domain endpoint exists within
Domain string
}
type Options struct {
Handler string
Namespace string
}
type Option func(o *Options)

View File

@@ -0,0 +1,90 @@
// Package subdomain is a resolver which uses the subdomain to determine the domain to route to. It
// offloads the endpoint resolution to a child resolver which is provided in New.
package subdomain
import (
"net"
"net/http"
"strings"
"github.com/unistack-org/micro/v3/api/resolver"
"github.com/unistack-org/micro/v3/logger"
"golang.org/x/net/publicsuffix"
)
// NewResolver creates new subdomain api resolver
func NewResolver(parent resolver.Resolver, opts ...resolver.Option) resolver.Resolver {
options := resolver.NewOptions(opts...)
return &subdomainResolver{options, parent}
}
type subdomainResolver struct {
opts resolver.Options
resolver.Resolver
}
// Resolve resolve endpoint based on subdomain
func (r *subdomainResolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) {
if dom := r.Domain(req); len(dom) > 0 {
opts = append(opts, resolver.Domain(dom))
}
return r.Resolver.Resolve(req, opts...)
}
// Domain returns domain
func (r *subdomainResolver) Domain(req *http.Request) string {
// determine the host, e.g. foobar.m3o.app
host := req.URL.Hostname()
if len(host) == 0 {
if h, _, err := net.SplitHostPort(req.Host); err == nil {
host = h // host does contain a port
} else if strings.Contains(err.Error(), "missing port in address") {
host = req.Host // host does not contain a port
}
}
// check for an ip address
if net.ParseIP(host) != nil {
return ""
}
// check for dev environment
if host == "localhost" || host == "127.0.0.1" {
return ""
}
// extract the top level domain plus one (e.g. 'myapp.com')
domain, err := publicsuffix.EffectiveTLDPlusOne(host)
if err != nil {
if logger.V(logger.DebugLevel) {
logger.Debug(r.opts.Context, "Unable to extract domain from %v", host)
}
return ""
}
// there was no subdomain
if host == domain {
return ""
}
// remove the domain from the host, leaving the subdomain, e.g. "staging.foo.myapp.com" => "staging.foo"
subdomain := strings.TrimSuffix(host, "."+domain)
// ignore the API subdomain
if subdomain == "api" {
return ""
}
// return the reversed subdomain as the namespace, e.g. "staging.foo" => "foo-staging"
comps := strings.Split(subdomain, ".")
for i := len(comps)/2 - 1; i >= 0; i-- {
opp := len(comps) - 1 - i
comps[i], comps[opp] = comps[opp], comps[i]
}
return strings.Join(comps, "-")
}
func (r *subdomainResolver) String() string {
return "subdomain"
}

View File

@@ -0,0 +1,73 @@
package subdomain
import (
"net/http"
"net/url"
"testing"
"github.com/unistack-org/micro/v3/api/resolver/vpath"
)
func TestResolve(t *testing.T) {
tt := []struct {
Name string
Host string
Result string
}{
{
Name: "Top level domain",
Host: "micro.mu",
Result: "micro",
},
{
Name: "Effective top level domain",
Host: "micro.com.au",
Result: "micro",
},
{
Name: "Subdomain dev",
Host: "dev.micro.mu",
Result: "dev",
},
{
Name: "Subdomain foo",
Host: "foo.micro.mu",
Result: "foo",
},
{
Name: "Multi-level subdomain",
Host: "staging.myapp.m3o.app",
Result: "myapp-staging",
},
{
Name: "Dev host",
Host: "127.0.0.1",
Result: "micro",
},
{
Name: "Localhost",
Host: "localhost",
Result: "micro",
},
{
Name: "IP host",
Host: "81.151.101.146",
Result: "micro",
},
}
for _, tc := range tt {
t.Run(tc.Name, func(t *testing.T) {
r := NewResolver(vpath.NewResolver())
result, err := r.Resolve(&http.Request{URL: &url.URL{Host: tc.Host, Path: "foo/bar"}})
if err != nil {
t.Fatal(err)
}
if result != nil {
if tc.Result != result.Domain {
t.Fatalf("Expected %v but got %v", tc.Result, result.Domain)
}
}
})
}
}

View File

@@ -7,53 +7,71 @@ import (
"regexp"
"strings"
"github.com/micro/go-micro/api/resolver"
"github.com/unistack-org/micro/v3/api/resolver"
)
type Resolver struct{}
// NewResolver creates new vpath api resolver
func NewResolver(opts ...resolver.Option) resolver.Resolver {
return &vpathResolver{opts: resolver.NewOptions(opts...)}
}
type vpathResolver struct {
opts resolver.Options
}
var (
re = regexp.MustCompile("^v[0-9]+$")
)
func (r *Resolver) Resolve(req *http.Request) (*resolver.Endpoint, error) {
// Resolve endpoint
func (r *vpathResolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) {
if req.URL.Path == "/" {
return nil, errors.New("unknown name")
}
parts := strings.Split(req.URL.Path[1:], "/")
options := resolver.NewResolveOptions(opts...)
parts := strings.Split(req.URL.Path[1:], "/")
if len(parts) == 1 {
return &resolver.Endpoint{
Name: parts[0],
Name: r.withPrefix(parts...),
Host: req.Host,
Method: req.Method,
Path: req.URL.Path,
Domain: options.Domain,
}, nil
}
// /v1/foo
if re.MatchString(parts[0]) {
return &resolver.Endpoint{
Name: parts[1],
Name: r.withPrefix(parts[0:2]...),
Host: req.Host,
Method: req.Method,
Path: req.URL.Path,
Domain: options.Domain,
}, nil
}
return &resolver.Endpoint{
Name: parts[0],
Name: r.withPrefix(parts[0]),
Host: req.Host,
Method: req.Method,
Path: req.URL.Path,
Domain: options.Domain,
}, nil
}
func (r *Resolver) String() string {
return "path"
func (r *vpathResolver) String() string {
return "vpath"
}
func NewResolver(opts ...resolver.Option) resolver.Resolver {
return &Resolver{}
// withPrefix transforms "foo" into "go.micro.api.foo"
func (r *vpathResolver) withPrefix(parts ...string) string {
p := r.opts.ServicePrefix
if len(p) > 0 {
parts = append([]string{p}, parts...)
}
return strings.Join(parts, ".")
}

View File

@@ -1,25 +1,36 @@
package router
import (
"github.com/micro/go-micro/api/resolver"
"github.com/micro/go-micro/api/resolver/micro"
"github.com/micro/go-micro/config/cmd"
"github.com/micro/go-micro/registry"
"context"
"github.com/unistack-org/micro/v3/api/resolver"
"github.com/unistack-org/micro/v3/api/resolver/vpath"
"github.com/unistack-org/micro/v3/logger"
"github.com/unistack-org/micro/v3/register"
)
// Options holds the options for api router
type Options struct {
Namespace string
Handler string
Registry registry.Registry
Resolver resolver.Resolver
// Register for service lookup
Register register.Register
// Resolver to use
Resolver resolver.Resolver
// Logger micro logger
Logger logger.Logger
// Context is for external options
Context context.Context
// Handler name
Handler string
}
// Option func signature
type Option func(o *Options)
// NewOptions returns options struct filled by opts
func NewOptions(opts ...Option) Options {
options := Options{
Handler: "meta",
Registry: *cmd.DefaultOptions().Registry,
Context: context.Background(),
Handler: "meta",
}
for _, o := range opts {
@@ -27,33 +38,36 @@ func NewOptions(opts ...Option) Options {
}
if options.Resolver == nil {
options.Resolver = micro.NewResolver(
options.Resolver = vpath.NewResolver(
resolver.WithHandler(options.Handler),
resolver.WithNamespace(options.Namespace),
)
}
return options
}
// WithContext sets the context
func WithContext(ctx context.Context) Option {
return func(o *Options) {
o.Context = ctx
}
}
// WithHandler sets the handler
func WithHandler(h string) Option {
return func(o *Options) {
o.Handler = h
}
}
func WithNamespace(ns string) Option {
// WithRegister sets the register
func WithRegister(r register.Register) Option {
return func(o *Options) {
o.Namespace = ns
}
}
func WithRegistry(r registry.Registry) Option {
return func(o *Options) {
o.Registry = r
o.Register = r
}
}
// WithResolver sets the resolver
func WithResolver(r resolver.Resolver) Option {
return func(o *Options) {
o.Resolver = r

View File

@@ -1,393 +0,0 @@
// Package registry provides a dynamic api service router
package registry
import (
"errors"
"fmt"
"log"
"net/http"
"regexp"
"strings"
"sync"
"time"
"github.com/micro/go-micro/api"
"github.com/micro/go-micro/api/router"
"github.com/micro/go-micro/registry"
"github.com/micro/go-micro/registry/cache"
)
// router is the default router
type registryRouter struct {
exit chan bool
opts router.Options
// registry cache
rc cache.Cache
sync.RWMutex
eps map[string]*api.Service
}
func setNamespace(ns, name string) string {
ns = strings.TrimSpace(ns)
name = strings.TrimSpace(name)
// no namespace
if len(ns) == 0 {
return name
}
switch {
// has - suffix
case strings.HasSuffix(ns, "-"):
return strings.Replace(ns+name, ".", "-", -1)
// has . suffix
case strings.HasSuffix(ns, "."):
return ns + name
}
// default join .
return strings.Join([]string{ns, name}, ".")
}
func (r *registryRouter) isClosed() bool {
select {
case <-r.exit:
return true
default:
return false
}
}
// refresh list of api services
func (r *registryRouter) refresh() {
var attempts int
for {
services, err := r.opts.Registry.ListServices()
if err != nil {
attempts++
log.Println("Error listing endpoints", err)
time.Sleep(time.Duration(attempts) * time.Second)
continue
}
attempts = 0
// for each service, get service and store endpoints
for _, s := range services {
// only get services for this namespace
if !strings.HasPrefix(s.Name, r.opts.Namespace) {
continue
}
service, err := r.rc.GetService(s.Name)
if err != nil {
continue
}
r.store(service)
}
// refresh list in 10 minutes... cruft
select {
case <-time.After(time.Minute * 10):
case <-r.exit:
return
}
}
}
// process watch event
func (r *registryRouter) process(res *registry.Result) {
// skip these things
if res == nil || res.Service == nil || !strings.HasPrefix(res.Service.Name, r.opts.Namespace) {
return
}
// get entry from cache
service, err := r.rc.GetService(res.Service.Name)
if err != nil {
return
}
// update our local endpoints
r.store(service)
}
// store local endpoint cache
func (r *registryRouter) store(services []*registry.Service) {
// endpoints
eps := map[string]*api.Service{}
// services
names := map[string]bool{}
// create a new endpoint mapping
for _, service := range services {
// set names we need later
names[service.Name] = true
// map per endpoint
for _, endpoint := range service.Endpoints {
// create a key service:endpoint_name
key := fmt.Sprintf("%s:%s", service.Name, endpoint.Name)
// decode endpoint
end := api.Decode(endpoint.Metadata)
// if we got nothing skip
if err := api.Validate(end); err != nil {
continue
}
// try get endpoint
ep, ok := eps[key]
if !ok {
ep = &api.Service{Name: service.Name}
}
// overwrite the endpoint
ep.Endpoint = end
// append services
ep.Services = append(ep.Services, service)
// store it
eps[key] = ep
}
}
r.Lock()
defer r.Unlock()
// delete any existing eps for services we know
for key, service := range r.eps {
// skip what we don't care about
if !names[service.Name] {
continue
}
// ok we know this thing
// delete delete delete
delete(r.eps, key)
}
// now set the eps we have
for name, endpoint := range eps {
r.eps[name] = endpoint
}
}
// watch for endpoint changes
func (r *registryRouter) watch() {
var attempts int
for {
if r.isClosed() {
return
}
// watch for changes
w, err := r.opts.Registry.Watch()
if err != nil {
attempts++
log.Println("Error watching endpoints", err)
time.Sleep(time.Duration(attempts) * time.Second)
continue
}
ch := make(chan bool)
go func() {
select {
case <-ch:
w.Stop()
case <-r.exit:
w.Stop()
}
}()
// reset if we get here
attempts = 0
for {
// process next event
res, err := w.Next()
if err != nil {
log.Println("Error getting next endpoint", err)
close(ch)
break
}
r.process(res)
}
}
}
func (r *registryRouter) Options() router.Options {
return r.opts
}
func (r *registryRouter) Close() error {
select {
case <-r.exit:
return nil
default:
close(r.exit)
r.rc.Stop()
}
return nil
}
func (r *registryRouter) Endpoint(req *http.Request) (*api.Service, error) {
if r.isClosed() {
return nil, errors.New("router closed")
}
r.RLock()
defer r.RUnlock()
// use the first match
// TODO: weighted matching
for _, e := range r.eps {
ep := e.Endpoint
// match
var pathMatch, hostMatch, methodMatch bool
// 1. try method GET, POST, PUT, etc
// 2. try host example.com, foobar.com, etc
// 3. try path /foo/bar, /bar/baz, etc
// 1. try match method
for _, m := range ep.Method {
if req.Method == m {
methodMatch = true
break
}
}
// no match on method pass
if len(ep.Method) > 0 && !methodMatch {
continue
}
// 2. try match host
for _, h := range ep.Host {
if req.Host == h {
hostMatch = true
break
}
}
// no match on host pass
if len(ep.Host) > 0 && !hostMatch {
continue
}
// 3. try match paths
for _, p := range ep.Path {
re, err := regexp.CompilePOSIX(p)
if err == nil && re.MatchString(req.URL.Path) {
pathMatch = true
break
}
}
// no match pass
if len(ep.Path) > 0 && !pathMatch {
continue
}
// TODO: Percentage traffic
// we got here, so its a match
return e, nil
}
// no match
return nil, errors.New("not found")
}
func (r *registryRouter) Route(req *http.Request) (*api.Service, error) {
if r.isClosed() {
return nil, errors.New("router closed")
}
// try get an endpoint
ep, err := r.Endpoint(req)
if err == nil {
return ep, nil
}
// error not nil
// ignore that shit
// TODO: don't ignore that shit
// get the service name
rp, err := r.opts.Resolver.Resolve(req)
if err != nil {
return nil, err
}
// service name
name := setNamespace(r.opts.Namespace, rp.Name)
// get service
services, err := r.rc.GetService(name)
if err != nil {
return nil, err
}
// only use endpoint matching when the meta handler is set aka api.Default
switch r.opts.Handler {
// rpc handlers
case "meta", "api", "rpc":
handler := r.opts.Handler
// set default handler to api
if r.opts.Handler == "meta" {
handler = "rpc"
}
// construct api service
return &api.Service{
Name: name,
Endpoint: &api.Endpoint{
Name: rp.Method,
Handler: handler,
},
Services: services,
}, nil
// http handler
case "http", "proxy", "web":
// construct api service
return &api.Service{
Name: name,
Endpoint: &api.Endpoint{
Name: req.URL.String(),
Handler: r.opts.Handler,
Host: []string{req.Host},
Method: []string{req.Method},
Path: []string{req.URL.Path},
},
Services: services,
}, nil
}
return nil, errors.New("unknown handler")
}
func newRouter(opts ...router.Option) *registryRouter {
options := router.NewOptions(opts...)
r := &registryRouter{
exit: make(chan bool),
opts: options,
rc: cache.New(options.Registry),
eps: make(map[string]*api.Service),
}
go r.watch()
go r.refresh()
return r
}
// NewRouter returns the default router
func NewRouter(opts ...router.Option) router.Router {
return newRouter(opts...)
}

View File

@@ -1,181 +0,0 @@
package registry
import (
"fmt"
"net/http"
"net/url"
"testing"
"github.com/micro/go-micro/api"
)
func TestSetNamespace(t *testing.T) {
testCases := []struct {
namespace string
name string
expected string
}{
// default dotted path
{
"go.micro.api",
"foo",
"go.micro.api.foo",
},
// dotted end
{
"go.micro.api.",
"foo",
"go.micro.api.foo",
},
// dashed end
{
"go-micro-api-",
"foo",
"go-micro-api-foo",
},
// no namespace
{
"",
"foo",
"foo",
},
{
"go-micro-api-",
"v2.foo",
"go-micro-api-v2-foo",
},
}
for _, test := range testCases {
name := setNamespace(test.namespace, test.name)
if name != test.expected {
t.Fatalf("expected name %s got %s", test.expected, name)
}
}
}
func TestRouter(t *testing.T) {
r := newRouter()
compare := func(expect, got []string) bool {
// no data to compare, return true
if len(expect) == 0 && len(got) == 0 {
return true
}
// no data expected but got some return false
if len(expect) == 0 && len(got) > 0 {
return false
}
// compare expected with what we got
for _, e := range expect {
var seen bool
for _, g := range got {
if e == g {
seen = true
break
}
}
if !seen {
return false
}
}
// we're done, return true
return true
}
testData := []struct {
e *api.Endpoint
r *http.Request
m bool
}{
{
e: &api.Endpoint{
Name: "Foo.Bar",
Host: []string{"example.com"},
Method: []string{"GET"},
Path: []string{"/foo"},
},
r: &http.Request{
Host: "example.com",
Method: "GET",
URL: &url.URL{
Path: "/foo",
},
},
m: true,
},
{
e: &api.Endpoint{
Name: "Bar.Baz",
Host: []string{"example.com", "foo.com"},
Method: []string{"GET", "POST"},
Path: []string{"/foo/bar"},
},
r: &http.Request{
Host: "foo.com",
Method: "POST",
URL: &url.URL{
Path: "/foo/bar",
},
},
m: true,
},
{
e: &api.Endpoint{
Name: "Test.Cruft",
Host: []string{"example.com", "foo.com"},
Method: []string{"GET", "POST"},
Path: []string{"/xyz"},
},
r: &http.Request{
Host: "fail.com",
Method: "DELETE",
URL: &url.URL{
Path: "/test/fail",
},
},
m: false,
},
}
for _, d := range testData {
key := fmt.Sprintf("%s:%s", "test.service", d.e.Name)
r.eps[key] = &api.Service{
Endpoint: d.e,
}
}
for _, d := range testData {
e, err := r.Endpoint(d.r)
if d.m && err != nil {
t.Fatalf("expected match, got %v", err)
}
if !d.m && err == nil {
t.Fatal("expected error got match")
}
// skip testing the non match
if !d.m {
continue
}
ep := e.Endpoint
// test the match
if d.e.Name != ep.Name {
t.Fatalf("expected %v got %v", d.e.Name, ep.Name)
}
if ok := compare(d.e.Method, ep.Method); !ok {
t.Fatalf("expected %v got %v", d.e.Method, ep.Method)
}
if ok := compare(d.e.Path, ep.Path); !ok {
t.Fatalf("expected %v got %v", d.e.Path, ep.Path)
}
if ok := compare(d.e.Host, ep.Host); !ok {
t.Fatalf("expected %v got %v", d.e.Host, ep.Host)
}
}
}

View File

@@ -4,17 +4,30 @@ package router
import (
"net/http"
"github.com/micro/go-micro/api"
"github.com/unistack-org/micro/v3/api"
)
var (
// DefaultRouter contains default router implementation
DefaultRouter Router
)
// Router is used to determine an endpoint for a request
type Router interface {
// Returns options
Options() Options
// Init initialize router
Init(...Option) error
// Stop the router
Close() error
// Endpoint returns an api.Service endpoint or an error if it does not exist
Endpoint(r *http.Request) (*api.Service, error)
// Register endpoint in router
Register(ep *api.Endpoint) error
// Deregister endpoint from router
Deregister(ep *api.Endpoint) error
// Route returns an api.Service route
Route(r *http.Request) (*api.Service, error)
// String representation of router
String() string
}

View File

@@ -1,24 +0,0 @@
// Package acme abstracts away various ACME libraries
package acme
import (
"errors"
"net"
)
var (
// ErrProviderNotImplemented can be returned when attempting to
// instantiate an unimplemented provider
ErrProviderNotImplemented = errors.New("Provider not implemented")
)
// Provider is a ACME provider interface
type Provider interface {
NewListener(...string) (net.Listener, error)
}
// The Let's Encrypt ACME endpoints
const (
LetsEncryptStagingCA = "https://acme-staging-v02.api.letsencrypt.org/directory"
LetsEncryptProductionCA = "https://acme-v02.api.letsencrypt.org/directory"
)

View File

@@ -1,23 +0,0 @@
// Package autocert is the ACME provider from golang.org/x/crypto/acme/autocert
// This provider does not take any config.
package autocert
import (
"net"
"github.com/micro/go-micro/api/server/acme"
"golang.org/x/crypto/acme/autocert"
)
// autoCertACME is the ACME provider from golang.org/x/crypto/acme/autocert
type autocertProvider struct{}
// NewListener implements acme.Provider
func (a *autocertProvider) NewListener(ACMEHosts ...string) (net.Listener, error) {
return autocert.NewListener(ACMEHosts...), nil
}
// New returns an autocert acme.Provider
func New() acme.Provider {
return &autocertProvider{}
}

View File

@@ -1,16 +0,0 @@
package autocert
import (
"testing"
)
func TestAutocert(t *testing.T) {
l := New()
if _, ok := l.(*autocertProvider); !ok {
t.Error("New() didn't return an autocertProvider")
}
// TODO: Travis CI doesn't let us bind :443
// if _, err := l.NewListener(); err != nil {
// t.Error(err.Error())
// }
}

View File

@@ -1,58 +0,0 @@
// Package certmagic is the ACME provider from github.com/mholt/certmagic
package certmagic
import (
"log"
"math/rand"
"net"
"time"
"github.com/mholt/certmagic"
"github.com/micro/go-micro/api/server/acme"
)
type certmagicProvider struct {
opts acme.Options
}
func (c *certmagicProvider) NewListener(ACMEHosts ...string) (net.Listener, error) {
certmagic.Default.CA = c.opts.CA
if c.opts.ChallengeProvider != nil {
// Enabling DNS Challenge disables the other challenges
certmagic.Default.DNSProvider = c.opts.ChallengeProvider
}
if c.opts.OnDemand {
certmagic.Default.OnDemand = new(certmagic.OnDemandConfig)
}
if c.opts.Cache != nil {
// already validated by new()
certmagic.Default.Storage = c.opts.Cache.(certmagic.Storage)
}
// If multiple instances of the provider are running, inject some
// randomness so they don't collide
rand.Seed(time.Now().UnixNano())
randomDuration := (7 * 24 * time.Hour) + (time.Duration(rand.Intn(504)) * time.Hour)
certmagic.Default.RenewDurationBefore = randomDuration
return certmagic.Listen(ACMEHosts)
}
// New returns a certmagic provider
func New(options ...acme.Option) acme.Provider {
opts := acme.DefaultOptions()
for _, o := range options {
o(&opts)
}
if opts.Cache != nil {
if _, ok := opts.Cache.(certmagic.Storage); !ok {
log.Fatal("ACME: cache provided doesn't implement certmagic's Storage interface")
}
}
return &certmagicProvider{
opts: opts,
}
}

View File

@@ -1,224 +0,0 @@
package certmagic
import (
"net/http"
"os"
"reflect"
"sort"
"testing"
"time"
"github.com/go-acme/lego/v3/providers/dns/cloudflare"
"github.com/mholt/certmagic"
"github.com/micro/go-micro/api/server/acme"
cfstore "github.com/micro/go-micro/store/cloudflare"
"github.com/micro/go-micro/sync/lock/memory"
)
func TestCertMagic(t *testing.T) {
if len(os.Getenv("IN_TRAVIS_CI")) != 0 {
t.Skip("Travis doesn't let us bind :443")
}
l, err := New().NewListener()
if err != nil {
t.Fatal(err.Error())
}
l.Close()
c := cloudflare.NewDefaultConfig()
c.AuthEmail = ""
c.AuthKey = ""
c.AuthToken = "test"
c.ZoneToken = "test"
p, err := cloudflare.NewDNSProviderConfig(c)
if err != nil {
t.Fatal(err.Error())
}
l, err = New(acme.AcceptToS(true),
acme.CA(acme.LetsEncryptStagingCA),
acme.ChallengeProvider(p),
).NewListener()
if err != nil {
t.Fatal(err.Error())
}
l.Close()
}
func TestStorageImplementation(t *testing.T) {
apiToken, accountID := os.Getenv("CF_API_TOKEN"), os.Getenv("CF_ACCOUNT_ID")
kvID := os.Getenv("KV_NAMESPACE_ID")
if len(apiToken) == 0 || len(accountID) == 0 || len(kvID) == 0 {
t.Skip("No Cloudflare API keys available, skipping test")
}
var s certmagic.Storage
st := cfstore.NewStore(
cfstore.Token(apiToken),
cfstore.Account(accountID),
cfstore.Namespace(kvID),
)
s = &storage{
lock: memory.NewLock(),
store: st,
}
// Test Lock
if err := s.Lock("test"); err != nil {
t.Fatal(err)
}
// Test Unlock
if err := s.Unlock("test"); err != nil {
t.Fatal(err)
}
// Test data
testdata := []struct {
key string
value []byte
}{
{key: "/foo/a", value: []byte("lorem")},
{key: "/foo/b", value: []byte("ipsum")},
{key: "/foo/c", value: []byte("dolor")},
{key: "/foo/d", value: []byte("sit")},
{key: "/bar/a", value: []byte("amet")},
{key: "/bar/b", value: []byte("consectetur")},
{key: "/bar/c", value: []byte("adipiscing")},
{key: "/bar/d", value: []byte("elit")},
{key: "/foo/bar/a", value: []byte("sed")},
{key: "/foo/bar/b", value: []byte("do")},
{key: "/foo/bar/c", value: []byte("eiusmod")},
{key: "/foo/bar/d", value: []byte("tempor")},
{key: "/foo/bar/baz/a", value: []byte("incididunt")},
{key: "/foo/bar/baz/b", value: []byte("ut")},
{key: "/foo/bar/baz/c", value: []byte("labore")},
{key: "/foo/bar/baz/d", value: []byte("et")},
// a duplicate just in case there's any edge cases
{key: "/foo/a", value: []byte("lorem")},
}
// Test Store
for _, d := range testdata {
if err := s.Store(d.key, d.value); err != nil {
t.Fatal(err.Error())
}
}
// Test Load
for _, d := range testdata {
if value, err := s.Load(d.key); err != nil {
t.Fatal(err.Error())
} else {
if !reflect.DeepEqual(value, d.value) {
t.Fatalf("Load %s: expected %v, got %v", d.key, d.value, value)
}
}
}
// Test Exists
for _, d := range testdata {
if !s.Exists(d.key) {
t.Fatalf("%s should exist, but doesn't\n", d.key)
}
}
// Test List
if list, err := s.List("/", true); err != nil {
t.Fatal(err.Error())
} else {
var expected []string
for i, d := range testdata {
if i != len(testdata)-1 {
// Don't store the intentionally duplicated key
expected = append(expected, d.key)
}
}
sort.Strings(expected)
sort.Strings(list)
if !reflect.DeepEqual(expected, list) {
t.Fatalf("List: Expected %v, got %v\n", expected, list)
}
}
if list, err := s.List("/foo", false); err != nil {
t.Fatal(err.Error())
} else {
sort.Strings(list)
expected := []string{"/foo/a", "/foo/b", "/foo/bar", "/foo/c", "/foo/d"}
if !reflect.DeepEqual(expected, list) {
t.Fatalf("List: expected %s, got %s\n", expected, list)
}
}
// Test Stat
for _, d := range testdata {
info, err := s.Stat(d.key)
if err != nil {
t.Fatal(err.Error())
} else {
if info.Key != d.key {
t.Fatalf("Stat().Key: expected %s, got %s\n", d.key, info.Key)
}
if info.Size != int64(len(d.value)) {
t.Fatalf("Stat().Size: expected %d, got %d\n", len(d.value), info.Size)
}
if time.Since(info.Modified) > time.Minute {
t.Fatalf("Stat().Modified: expected time since last modified to be < 1 minute, got %v\n", time.Since(info.Modified))
}
}
}
// Test Delete
for _, d := range testdata {
if err := s.Delete(d.key); err != nil {
t.Fatal(err.Error())
}
}
// New interface doesn't return an error, so call it in case any log.Fatal
// happens
New(acme.Cache(s))
}
// Full test with a real zone, with against LE staging
func TestE2e(t *testing.T) {
apiToken, accountID := os.Getenv("CF_API_TOKEN"), os.Getenv("CF_ACCOUNT_ID")
kvID := os.Getenv("KV_NAMESPACE_ID")
if len(apiToken) == 0 || len(accountID) == 0 || len(kvID) == 0 {
t.Skip("No Cloudflare API keys available, skipping test")
}
testLock := memory.NewLock()
testStore := cfstore.NewStore(
cfstore.Token(apiToken),
cfstore.Account(accountID),
cfstore.Namespace(kvID),
)
testStorage := NewStorage(testLock, testStore)
conf := cloudflare.NewDefaultConfig()
conf.AuthToken = apiToken
conf.ZoneToken = apiToken
testChallengeProvider, err := cloudflare.NewDNSProviderConfig(conf)
if err != nil {
t.Fatal(err.Error())
}
testProvider := New(
acme.AcceptToS(true),
acme.Cache(testStorage),
acme.CA(acme.LetsEncryptStagingCA),
acme.ChallengeProvider(testChallengeProvider),
acme.OnDemand(false),
)
listener, err := testProvider.NewListener("*.micro.mu", "micro.mu")
if err != nil {
t.Fatal(err.Error())
}
go http.Serve(listener, http.NotFoundHandler())
time.Sleep(10 * time.Minute)
}

View File

@@ -1,146 +0,0 @@
package certmagic
import (
"bytes"
"encoding/gob"
"errors"
"fmt"
"path"
"strings"
"time"
"github.com/mholt/certmagic"
"github.com/micro/go-micro/store"
"github.com/micro/go-micro/sync/lock"
)
// File represents a "File" that will be stored in store.Store - the contents and last modified time
type File struct {
// last modified time
LastModified time.Time
// Contents
Contents []byte
}
// storage is an implementation of certmagic.Storage using micro's sync.Map and store.Store interfaces.
// As certmagic storage expects a filesystem (with stat() abilities) we have to implement
// the bare minimum of metadata.
type storage struct {
lock lock.Lock
store store.Store
}
func (s *storage) Lock(key string) error {
return s.lock.Acquire(key, lock.TTL(10*time.Minute))
}
func (s *storage) Unlock(key string) error {
return s.lock.Release(key)
}
func (s *storage) Store(key string, value []byte) error {
f := File{
LastModified: time.Now(),
Contents: value,
}
buf := &bytes.Buffer{}
e := gob.NewEncoder(buf)
if err := e.Encode(f); err != nil {
return err
}
r := &store.Record{
Key: key,
Value: buf.Bytes(),
}
return s.store.Write(r)
}
func (s *storage) Load(key string) ([]byte, error) {
if !s.Exists(key) {
return nil, certmagic.ErrNotExist(errors.New(key + " doesn't exist"))
}
records, err := s.store.Read(key)
if err != nil {
return nil, err
}
if len(records) != 1 {
return nil, fmt.Errorf("ACME Storage: multiple records matched key %s", key)
}
b := bytes.NewBuffer(records[0].Value)
d := gob.NewDecoder(b)
var f File
err = d.Decode(&f)
if err != nil {
return nil, err
}
return f.Contents, nil
}
func (s *storage) Delete(key string) error {
return s.store.Delete(key)
}
func (s *storage) Exists(key string) bool {
_, err := s.store.Read(key)
if err != nil {
return false
}
return true
}
func (s *storage) List(prefix string, recursive bool) ([]string, error) {
records, err := s.store.List()
if err != nil {
return nil, err
}
var results []string
for _, r := range records {
if strings.HasPrefix(r.Key, prefix) {
results = append(results, r.Key)
}
}
if recursive {
return results, nil
}
keysMap := make(map[string]bool)
for _, key := range results {
dir := strings.Split(strings.TrimPrefix(key, prefix+"/"), "/")
keysMap[dir[0]] = true
}
results = make([]string, 0)
for k := range keysMap {
results = append(results, path.Join(prefix, k))
}
return results, nil
}
func (s *storage) Stat(key string) (certmagic.KeyInfo, error) {
records, err := s.store.Read(key)
if err != nil {
return certmagic.KeyInfo{}, err
}
if len(records) != 1 {
return certmagic.KeyInfo{}, fmt.Errorf("ACME Storage: multiple records matched key %s", key)
}
b := bytes.NewBuffer(records[0].Value)
d := gob.NewDecoder(b)
var f File
err = d.Decode(&f)
if err != nil {
return certmagic.KeyInfo{}, err
}
return certmagic.KeyInfo{
Key: key,
Modified: f.LastModified,
Size: int64(len(f.Contents)),
IsTerminal: false,
}, nil
}
// NewStorage returns a certmagic.Storage backed by a go-micro/lock and go-micro/store
func NewStorage(lock lock.Lock, store store.Store) certmagic.Storage {
return &storage{
lock: lock,
store: store,
}
}

View File

@@ -1,73 +0,0 @@
package acme
import "github.com/go-acme/lego/v3/challenge"
// Option (or Options) are passed to New() to configure providers
type Option func(o *Options)
// Options represents various options you can present to ACME providers
type Options struct {
// AcceptTLS must be set to true to indicate that you have read your
// provider's terms of service.
AcceptToS bool
// CA is the CA to use
CA string
// ChallengeProvider is a go-acme/lego challenge provider. Set this if you
// want to use DNS Challenges. Otherwise, tls-alpn-01 will be used
ChallengeProvider challenge.Provider
// Issue certificates for domains on demand. Otherwise, certs will be
// retrieved / issued on start-up.
OnDemand bool
// Cache is a storage interface. Most ACME libraries have an cache, but
// there's no defined interface, so if you consume this option
// sanity check it before using.
Cache interface{}
}
// AcceptToS indicates whether you accept your CA's terms of service
func AcceptToS(b bool) Option {
return func(o *Options) {
o.AcceptToS = b
}
}
// CA sets the CA of an acme.Options
func CA(CA string) Option {
return func(o *Options) {
o.CA = CA
}
}
// ChallengeProvider sets the Challenge provider of an acme.Options
// if set, it enables the DNS challenge, otherwise tls-alpn-01 will be used.
func ChallengeProvider(p challenge.Provider) Option {
return func(o *Options) {
o.ChallengeProvider = p
}
}
// OnDemand enables on-demand certificate issuance. Not recommended for use
// with the DNS challenge, as the first connection may be very slow.
func OnDemand(b bool) Option {
return func(o *Options) {
o.OnDemand = b
}
}
// Cache provides a cache / storage interface to the underlying ACME library
// as there is no standard, this needs to be validated by the underlying
// implentation.
func Cache(c interface{}) Option {
return func(o *Options) {
o.Cache = c
}
}
// DefaultOptions uses the Let's Encrypt Production CA, with DNS Challenge disabled.
func DefaultOptions() Options {
return Options{
AcceptToS: true,
CA: LetsEncryptProductionCA,
OnDemand: true,
}
}

View File

@@ -1,97 +0,0 @@
// Package http provides a http server with features; acme, cors, etc
package http
import (
"crypto/tls"
"net"
"net/http"
"os"
"sync"
"github.com/gorilla/handlers"
"github.com/micro/go-micro/api/server"
"github.com/micro/go-micro/util/log"
)
type httpServer struct {
mux *http.ServeMux
opts server.Options
mtx sync.RWMutex
address string
exit chan chan error
}
func NewServer(address string) server.Server {
return &httpServer{
opts: server.Options{},
mux: http.NewServeMux(),
address: address,
exit: make(chan chan error),
}
}
func (s *httpServer) Address() string {
s.mtx.RLock()
defer s.mtx.RUnlock()
return s.address
}
func (s *httpServer) Init(opts ...server.Option) error {
for _, o := range opts {
o(&s.opts)
}
return nil
}
func (s *httpServer) Handle(path string, handler http.Handler) {
s.mux.Handle(path, handlers.CombinedLoggingHandler(os.Stdout, handler))
}
func (s *httpServer) Start() error {
var l net.Listener
var err error
if s.opts.EnableACME && s.opts.ACMEProvider != nil {
// should we check the address to make sure its using :443?
l, err = s.opts.ACMEProvider.NewListener(s.opts.ACMEHosts...)
} else if s.opts.EnableTLS && s.opts.TLSConfig != nil {
l, err = tls.Listen("tcp", s.address, s.opts.TLSConfig)
} else {
// otherwise plain listen
l, err = net.Listen("tcp", s.address)
}
if err != nil {
return err
}
log.Logf("HTTP API Listening on %s", l.Addr().String())
s.mtx.Lock()
s.address = l.Addr().String()
s.mtx.Unlock()
go func() {
if err := http.Serve(l, s.mux); err != nil {
// temporary fix
//log.Fatal(err)
}
}()
go func() {
ch := <-s.exit
ch <- l.Close()
}()
return nil
}
func (s *httpServer) Stop() error {
ch := make(chan error)
s.exit <- ch
return <-ch
}
func (s *httpServer) String() string {
return "http"
}

View File

@@ -1,41 +0,0 @@
package http
import (
"fmt"
"io/ioutil"
"net/http"
"testing"
)
func TestHTTPServer(t *testing.T) {
testResponse := "hello world"
s := NewServer("localhost:0")
s.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, testResponse)
}))
if err := s.Start(); err != nil {
t.Fatal(err)
}
rsp, err := http.Get(fmt.Sprintf("http://%s/", s.Address()))
if err != nil {
t.Fatal(err)
}
defer rsp.Body.Close()
b, err := ioutil.ReadAll(rsp.Body)
if err != nil {
t.Fatal(err)
}
if string(b) != testResponse {
t.Fatalf("Unexpected response, got %s, expected %s", string(b), testResponse)
}
if err := s.Stop(); err != nil {
t.Fatal(err)
}
}

View File

@@ -1,47 +0,0 @@
package server
import (
"crypto/tls"
"github.com/micro/go-micro/api/server/acme"
)
type Option func(o *Options)
type Options struct {
EnableACME bool
ACMEProvider acme.Provider
EnableTLS bool
ACMEHosts []string
TLSConfig *tls.Config
}
func EnableACME(b bool) Option {
return func(o *Options) {
o.EnableACME = b
}
}
func ACMEHosts(hosts ...string) Option {
return func(o *Options) {
o.ACMEHosts = hosts
}
}
func ACMEProvider(p acme.Provider) Option {
return func(o *Options) {
o.ACMEProvider = p
}
}
func EnableTLS(b bool) Option {
return func(o *Options) {
o.EnableTLS = b
}
}
func TLSConfig(t *tls.Config) Option {
return func(o *Options) {
o.TLSConfig = t
}
}

View File

@@ -1,15 +0,0 @@
// Package server provides an API gateway server which handles inbound requests
package server
import (
"net/http"
)
// Server serves api requests
type Server interface {
Address() string
Init(opts ...Option) error
Handle(path string, handler http.Handler)
Start() error
Stop() error
}

141
auth/auth.go Normal file
View File

@@ -0,0 +1,141 @@
// Package auth provides authentication and authorization capability
package auth
import (
"context"
"errors"
"time"
"github.com/unistack-org/micro/v3/metadata"
)
const (
// BearerScheme used for Authorization header
BearerScheme = "Bearer "
// ScopePublic is the scope applied to a rule to allow access to the public
ScopePublic = ""
// ScopeAccount is the scope applied to a rule to limit to users with any valid account
ScopeAccount = "*"
)
var (
// DefaultAuth holds default auth implementation
DefaultAuth Auth = NewAuth()
// ErrInvalidToken is when the token provided is not valid
ErrInvalidToken = errors.New("invalid token provided")
// ErrForbidden is when a user does not have the necessary scope to access a resource
ErrForbidden = errors.New("resource forbidden")
)
// Auth provides authentication and authorization
type Auth interface {
// Init the auth
Init(opts ...Option) error
// Options set for auth
Options() Options
// Generate a new account
Generate(id string, opts ...GenerateOption) (*Account, error)
// Verify an account has access to a resource using the rules
Verify(acc *Account, res *Resource, opts ...VerifyOption) error
// Inspect a token
Inspect(token string) (*Account, error)
// Token generated using refresh token or credentials
Token(opts ...TokenOption) (*Token, error)
// Grant access to a resource
Grant(rule *Rule) error
// Revoke access to a resource
Revoke(rule *Rule) error
// Rules returns all the rules used to verify requests
Rules(...RulesOption) ([]*Rule, error)
// String returns the name of the implementation
String() string
}
// Account provided by an auth provider
type Account struct {
// Metadata any other associated metadata
Metadata metadata.Metadata `json:"metadata"`
// ID of the account e.g. email or uuid
ID string `json:"id"`
// Type of the account, e.g. service
Type string `json:"type"`
// Issuer of the account
Issuer string `json:"issuer"`
// Secret for the account, e.g. the password
Secret string `json:"secret"`
// Scopes the account has access to
Scopes []string `json:"scopes"`
}
// Token can be short or long lived
type Token struct {
// Time of token creation
Created time.Time `json:"created"`
// Time of token expiry
Expiry time.Time `json:"expiry"`
// The token to be used for accessing resources
AccessToken string `json:"access_token"`
// RefreshToken to be used to generate a new token
RefreshToken string `json:"refresh_token"`
}
// Expired returns a boolean indicating if the token needs to be refreshed
func (t *Token) Expired() bool {
return t.Expiry.Unix() < time.Now().Unix()
}
// Resource is an entity such as a user or
type Resource struct {
// Name of the resource, e.g. go.micro.service.notes
Name string `json:"name"`
// Type of resource, e.g. service
Type string `json:"type"`
// Endpoint resource e.g NotesService.Create
Endpoint string `json:"endpoint"`
}
// Access defines the type of access a rule grants
type Access int
const (
// AccessGranted to a resource
AccessGranted Access = iota
// AccessDenied to a resource
AccessDenied
)
// Rule is used to verify access to a resource
type Rule struct {
// Resource that rule belongs to
Resource *Resource
// ID of the rule
ID string
// Scope of the rule
Scope string
// Access flag allow/deny
Access Access
// Priority holds the rule priority
Priority int32
}
type accountKey struct{}
// AccountFromContext gets the account from the context, which
// is set by the auth wrapper at the start of a call. If the account
// is not set, a nil account will be returned. The error is only returned
// when there was a problem retrieving an account
func AccountFromContext(ctx context.Context) (*Account, bool) {
if ctx == nil {
return nil, false
}
acc, ok := ctx.Value(accountKey{}).(*Account)
return acc, ok
}
// ContextWithAccount sets the account in the context
func ContextWithAccount(ctx context.Context, account *Account) context.Context {
if ctx == nil {
ctx = context.Background()
}
return context.WithValue(ctx, accountKey{}, account)
}

79
auth/noop.go Normal file
View File

@@ -0,0 +1,79 @@
package auth
import (
"github.com/google/uuid"
)
type noopAuth struct {
opts Options
}
// String returns the name of the implementation
func (n *noopAuth) String() string {
return "noop"
}
// Init the auth
func (n *noopAuth) Init(opts ...Option) error {
for _, o := range opts {
o(&n.opts)
}
return nil
}
// Options set for auth
func (n *noopAuth) Options() Options {
return n.opts
}
// Generate a new account
func (n *noopAuth) Generate(id string, opts ...GenerateOption) (*Account, error) {
options := NewGenerateOptions(opts...)
return &Account{
ID: id,
Secret: options.Secret,
Metadata: options.Metadata,
Scopes: options.Scopes,
Issuer: n.Options().Issuer,
}, nil
}
// Grant access to a resource
func (n *noopAuth) Grant(rule *Rule) error {
return nil
}
// Revoke access to a resource
func (n *noopAuth) Revoke(rule *Rule) error {
return nil
}
// Rules used to verify requests
func (n *noopAuth) Rules(opts ...RulesOption) ([]*Rule, error) {
return []*Rule{}, nil
}
// Verify an account has access to a resource
func (n *noopAuth) Verify(acc *Account, res *Resource, opts ...VerifyOption) error {
return nil
}
// Inspect a token
func (n *noopAuth) Inspect(token string) (*Account, error) {
uid, err := uuid.NewRandom()
if err != nil {
return nil, err
}
return &Account{ID: uid.String(), Issuer: n.Options().Issuer}, nil
}
// Token generation using an account id and secret
func (n *noopAuth) Token(opts ...TokenOption) (*Token, error) {
return &Token{}, nil
}
// NewAuth returns new noop auth
func NewAuth(opts ...Option) Auth {
return &noopAuth{opts: NewOptions(opts...)}
}

311
auth/options.go Normal file
View File

@@ -0,0 +1,311 @@
package auth
import (
"context"
"time"
"github.com/unistack-org/micro/v3/logger"
"github.com/unistack-org/micro/v3/metadata"
"github.com/unistack-org/micro/v3/meter"
"github.com/unistack-org/micro/v3/store"
"github.com/unistack-org/micro/v3/tracer"
)
// NewOptions creates Options struct from slice of options
func NewOptions(opts ...Option) Options {
options := Options{
Tracer: tracer.DefaultTracer,
Logger: logger.DefaultLogger,
Meter: meter.DefaultMeter,
}
for _, o := range opts {
o(&options)
}
return options
}
// Options struct holds auth options
type Options struct {
// Context holds the external options
Context context.Context
// Meter used for metrics
Meter meter.Meter
// Logger used for logging
Logger logger.Logger
// Tracer used for tracing
Tracer tracer.Tracer
// Store used for stre data
Store store.Store
// Token is the services token used to authenticate itself
Token *Token
// LoginURL is the relative url path where a user can login
LoginURL string
// PrivateKey for encoding JWTs
PrivateKey string
// PublicKey for decoding JWTs
PublicKey string
// Secret is used to authenticate the service
Secret string
// ID is the services auth ID
ID string
// Issuer of the service's account
Issuer string
// Name holds the auth name
Name string
// Addrs sets the addresses of auth
Addrs []string
}
// Option func
type Option func(o *Options)
// Addrs is the auth addresses to use
func Addrs(addrs ...string) Option {
return func(o *Options) {
o.Addrs = addrs
}
}
// Name sets the name
func Name(n string) Option {
return func(o *Options) {
o.Name = n
}
}
// Issuer of the services account
func Issuer(i string) Option {
return func(o *Options) {
o.Issuer = i
}
}
// Store to back auth
func Store(s store.Store) Option {
return func(o *Options) {
o.Store = s
}
}
// PublicKey is the JWT public key
func PublicKey(key string) Option {
return func(o *Options) {
o.PublicKey = key
}
}
// PrivateKey is the JWT private key
func PrivateKey(key string) Option {
return func(o *Options) {
o.PrivateKey = key
}
}
// Credentials sets the auth credentials
func Credentials(id, secret string) Option {
return func(o *Options) {
o.ID = id
o.Secret = secret
}
}
// ClientToken sets the auth token to use when making requests
func ClientToken(token *Token) Option {
return func(o *Options) {
o.Token = token
}
}
// LoginURL sets the auth LoginURL
func LoginURL(url string) Option {
return func(o *Options) {
o.LoginURL = url
}
}
// GenerateOptions struct
type GenerateOptions struct {
Metadata metadata.Metadata
Provider string
Type string
Secret string
Issuer string
Scopes []string
}
// GenerateOption func
type GenerateOption func(o *GenerateOptions)
// WithSecret for the generated account
func WithSecret(s string) GenerateOption {
return func(o *GenerateOptions) {
o.Secret = s
}
}
// WithType for the generated account
func WithType(t string) GenerateOption {
return func(o *GenerateOptions) {
o.Type = t
}
}
// WithMetadata for the generated account
func WithMetadata(md metadata.Metadata) GenerateOption {
return func(o *GenerateOptions) {
o.Metadata = metadata.Copy(md)
}
}
// WithProvider for the generated account
func WithProvider(p string) GenerateOption {
return func(o *GenerateOptions) {
o.Provider = p
}
}
// WithScopes for the generated account
func WithScopes(s ...string) GenerateOption {
return func(o *GenerateOptions) {
o.Scopes = s
}
}
// WithIssuer for the generated account
func WithIssuer(i string) GenerateOption {
return func(o *GenerateOptions) {
o.Issuer = i
}
}
// NewGenerateOptions from a slice of options
func NewGenerateOptions(opts ...GenerateOption) GenerateOptions {
var options GenerateOptions
for _, o := range opts {
o(&options)
}
return options
}
// TokenOptions struct
type TokenOptions struct {
ID string
Secret string
RefreshToken string
Issuer string
Expiry time.Duration
}
// TokenOption func
type TokenOption func(o *TokenOptions)
// WithExpiry for the token
func WithExpiry(ex time.Duration) TokenOption {
return func(o *TokenOptions) {
o.Expiry = ex
}
}
// WithCredentials sets tye id and secret
func WithCredentials(id, secret string) TokenOption {
return func(o *TokenOptions) {
o.ID = id
o.Secret = secret
}
}
// WithToken sets the refresh token
func WithToken(rt string) TokenOption {
return func(o *TokenOptions) {
o.RefreshToken = rt
}
}
// WithTokenIssuer sets the token issuer option
func WithTokenIssuer(iss string) TokenOption {
return func(o *TokenOptions) {
o.Issuer = iss
}
}
// NewTokenOptions from a slice of options
func NewTokenOptions(opts ...TokenOption) TokenOptions {
var options TokenOptions
for _, o := range opts {
o(&options)
}
// set default expiry of token
if options.Expiry == 0 {
options.Expiry = time.Minute
}
return options
}
// VerifyOptions struct
type VerifyOptions struct {
Context context.Context
Namespace string
}
// VerifyOption func
type VerifyOption func(o *VerifyOptions)
// VerifyContext pass context to verify
func VerifyContext(ctx context.Context) VerifyOption {
return func(o *VerifyOptions) {
o.Context = ctx
}
}
// VerifyNamespace sets thhe namespace for verify
func VerifyNamespace(ns string) VerifyOption {
return func(o *VerifyOptions) {
o.Namespace = ns
}
}
// RulesOptions struct
type RulesOptions struct {
Context context.Context
Namespace string
}
// RulesOption func
type RulesOption func(o *RulesOptions)
// RulesContext pass rules context
func RulesContext(ctx context.Context) RulesOption {
return func(o *RulesOptions) {
o.Context = ctx
}
}
// RulesNamespace sets the rule namespace
func RulesNamespace(ns string) RulesOption {
return func(o *RulesOptions) {
o.Namespace = ns
}
}
// Logger sets the logger
func Logger(l logger.Logger) Option {
return func(o *Options) {
o.Logger = l
}
}
// Meter sets the meter
func Meter(m meter.Meter) Option {
return func(o *Options) {
o.Meter = m
}
}
// Tracer sets the meter
func Tracer(t tracer.Tracer) Option {
return func(o *Options) {
o.Tracer = t
}
}

92
auth/rules.go Normal file
View File

@@ -0,0 +1,92 @@
package auth
import (
"fmt"
"sort"
"strings"
)
// VerifyAccess an account has access to a resource using the rules provided. If the account does not have
// access an error will be returned. If there are no rules provided which match the resource, an error
// will be returned
//nolint:gocyclo
func VerifyAccess(rules []*Rule, acc *Account, res *Resource) error {
// the rule is only to be applied if the type matches the resource or is catch-all (*)
validTypes := []string{"*", res.Type}
// the rule is only to be applied if the name matches the resource or is catch-all (*)
validNames := []string{"*", res.Name}
// rules can have wildcard excludes on endpoints since this can also be a path for web services,
// e.g. /foo/* would include /foo/bar. We also want to check for wildcards and the exact endpoint
validEndpoints := []string{"*", res.Endpoint}
if comps := strings.Split(res.Endpoint, "/"); len(comps) > 1 {
for i := 1; i < len(comps)+1; i++ {
wildcard := fmt.Sprintf("%v/*", strings.Join(comps[0:i], "/"))
validEndpoints = append(validEndpoints, wildcard)
}
}
// filter the rules to the ones which match the criteria above
filteredRules := make([]*Rule, 0)
for _, rule := range rules {
if !include(validTypes, rule.Resource.Type) {
continue
}
if !include(validNames, rule.Resource.Name) {
continue
}
if !include(validEndpoints, rule.Resource.Endpoint) {
continue
}
filteredRules = append(filteredRules, rule)
}
// sort the filtered rules by priority, highest to lowest
sort.SliceStable(filteredRules, func(i, j int) bool {
return filteredRules[i].Priority > filteredRules[j].Priority
})
// loop through the rules and check for a rule which applies to this account
for _, rule := range filteredRules {
// a blank scope indicates the rule applies to everyone, even nil accounts
if rule.Scope == ScopePublic && rule.Access == AccessDenied {
return ErrForbidden
} else if rule.Scope == ScopePublic && rule.Access == AccessGranted {
return nil
}
// all further checks require an account
if acc == nil {
continue
}
// this rule applies to any account
if rule.Scope == ScopeAccount && rule.Access == AccessDenied {
return ErrForbidden
} else if rule.Scope == ScopeAccount && rule.Access == AccessGranted {
return nil
}
// if the account has the necessary scope
if include(acc.Scopes, rule.Scope) && rule.Access == AccessDenied {
return ErrForbidden
} else if include(acc.Scopes, rule.Scope) && rule.Access == AccessGranted {
return nil
}
}
// if no rules matched then return forbidden
return ErrForbidden
}
// include is a helper function which checks to see if the slice contains the value. includes is
// not case sensitive.
func include(slice []string, val string) bool {
for _, s := range slice {
if strings.EqualFold(s, val) {
return true
}
}
return false
}

288
auth/rules_test.go Normal file
View File

@@ -0,0 +1,288 @@
package auth
import (
"testing"
)
func TestVerify(t *testing.T) {
srvResource := &Resource{
Type: "service",
Name: "go.micro.service.foo",
Endpoint: "Foo.Bar",
}
webResource := &Resource{
Type: "service",
Name: "go.micro.web.foo",
Endpoint: "/foo/bar",
}
catchallResource := &Resource{
Type: "*",
Name: "*",
Endpoint: "*",
}
tt := []struct {
Name string
Rules []*Rule
Account *Account
Resource *Resource
Error error
}{
{
Name: "NoRules",
Rules: []*Rule{},
Account: nil,
Resource: srvResource,
Error: ErrForbidden,
},
{
Name: "CatchallPublicAccount",
Account: &Account{},
Resource: srvResource,
Rules: []*Rule{
{
Scope: "",
Resource: catchallResource,
},
},
},
{
Name: "CatchallPublicNoAccount",
Resource: srvResource,
Rules: []*Rule{
{
Scope: "",
Resource: catchallResource,
},
},
},
{
Name: "CatchallPrivateAccount",
Account: &Account{},
Resource: srvResource,
Rules: []*Rule{
{
Scope: "*",
Resource: catchallResource,
},
},
},
{
Name: "CatchallPrivateNoAccount",
Resource: srvResource,
Rules: []*Rule{
{
Scope: "*",
Resource: catchallResource,
},
},
Error: ErrForbidden,
},
{
Name: "CatchallServiceRuleMatch",
Resource: srvResource,
Account: &Account{},
Rules: []*Rule{
{
Scope: "*",
Resource: &Resource{
Type: srvResource.Type,
Name: srvResource.Name,
Endpoint: "*",
},
},
},
},
{
Name: "CatchallServiceRuleNoMatch",
Resource: srvResource,
Account: &Account{},
Rules: []*Rule{
{
Scope: "*",
Resource: &Resource{
Type: srvResource.Type,
Name: "wrongname",
Endpoint: "*",
},
},
},
Error: ErrForbidden,
},
{
Name: "ExactRuleValidScope",
Resource: srvResource,
Account: &Account{
Scopes: []string{"neededscope"},
},
Rules: []*Rule{
{
Scope: "neededscope",
Resource: srvResource,
},
},
},
{
Name: "ExactRuleInvalidScope",
Resource: srvResource,
Account: &Account{
Scopes: []string{"neededscope"},
},
Rules: []*Rule{
{
Scope: "invalidscope",
Resource: srvResource,
},
},
Error: ErrForbidden,
},
{
Name: "CatchallDenyWithAccount",
Resource: srvResource,
Account: &Account{},
Rules: []*Rule{
{
Scope: "*",
Resource: catchallResource,
Access: AccessDenied,
},
},
Error: ErrForbidden,
},
{
Name: "CatchallDenyWithNoAccount",
Resource: srvResource,
Account: &Account{},
Rules: []*Rule{
{
Scope: "*",
Resource: catchallResource,
Access: AccessDenied,
},
},
Error: ErrForbidden,
},
{
Name: "RulePriorityGrantFirst",
Resource: srvResource,
Account: &Account{},
Rules: []*Rule{
{
Scope: "*",
Resource: catchallResource,
Access: AccessGranted,
Priority: 1,
},
{
Scope: "*",
Resource: catchallResource,
Access: AccessDenied,
Priority: 0,
},
},
},
{
Name: "RulePriorityDenyFirst",
Resource: srvResource,
Account: &Account{},
Rules: []*Rule{
{
Scope: "*",
Resource: catchallResource,
Access: AccessGranted,
Priority: 0,
},
{
Scope: "*",
Resource: catchallResource,
Access: AccessDenied,
Priority: 1,
},
},
Error: ErrForbidden,
},
{
Name: "WebExactEndpointValid",
Resource: webResource,
Account: &Account{},
Rules: []*Rule{
{
Scope: "*",
Resource: webResource,
},
},
},
{
Name: "WebExactEndpointInalid",
Resource: webResource,
Account: &Account{},
Rules: []*Rule{
{
Scope: "*",
Resource: &Resource{
Type: webResource.Type,
Name: webResource.Name,
Endpoint: "invalidendpoint",
},
},
},
Error: ErrForbidden,
},
{
Name: "WebWildcardEndpoint",
Resource: webResource,
Account: &Account{},
Rules: []*Rule{
{
Scope: "*",
Resource: &Resource{
Type: webResource.Type,
Name: webResource.Name,
Endpoint: "*",
},
},
},
},
{
Name: "WebWildcardPathEndpointValid",
Resource: webResource,
Account: &Account{},
Rules: []*Rule{
{
Scope: "*",
Resource: &Resource{
Type: webResource.Type,
Name: webResource.Name,
Endpoint: "/foo/*",
},
},
},
},
{
Name: "WebWildcardPathEndpointInvalid",
Resource: webResource,
Account: &Account{},
Rules: []*Rule{
{
Scope: "*",
Resource: &Resource{
Type: webResource.Type,
Name: webResource.Name,
Endpoint: "/bar/*",
},
},
},
Error: ErrForbidden,
},
}
for _, tc := range tt {
t.Run(tc.Name, func(t *testing.T) {
if err := VerifyAccess(tc.Rules, tc.Account, tc.Resource); err != tc.Error {
t.Errorf("Expected %v but got %v", tc.Error, err)
}
})
}
}

View File

@@ -1,70 +1,50 @@
// Package broker is an interface used for asynchronous messaging
package broker
import (
"context"
"github.com/unistack-org/micro/v3/metadata"
)
var (
// DefaultBroker default broker
DefaultBroker Broker = NewBroker()
)
// Broker is an interface used for asynchronous messaging.
type Broker interface {
Name() string
Init(...Option) error
Options() Options
Address() string
Connect() error
Disconnect() error
Publish(topic string, m *Message, opts ...PublishOption) error
Subscribe(topic string, h Handler, opts ...SubscribeOption) (Subscriber, error)
Connect(context.Context) error
Disconnect(context.Context) error
Publish(context.Context, string, *Message, ...PublishOption) error
Subscribe(context.Context, string, Handler, ...SubscribeOption) (Subscriber, error)
String() string
}
// Handler is used to process messages via a subscription of a topic.
// The handler is passed a publication interface which contains the
// message and optional Ack method to acknowledge receipt of the message.
type Handler func(Event) error
type Message struct {
Header map[string]string
Body []byte
}
// Event is given to a subscription handler for processing
type Event interface {
Topic() string
Message() *Message
Ack() error
Error() error
}
// Message is used to transfer data
type Message struct {
Header metadata.Metadata // contains message metadata
Body []byte // contains message body
}
// Subscriber is a convenience return type for the Subscribe method
type Subscriber interface {
Options() SubscribeOptions
Topic() string
Unsubscribe() error
}
var (
DefaultBroker Broker = newHttpBroker()
)
func NewBroker(opts ...Option) Broker {
return newHttpBroker(opts...)
}
func Init(opts ...Option) error {
return DefaultBroker.Init(opts...)
}
func Connect() error {
return DefaultBroker.Connect()
}
func Disconnect() error {
return DefaultBroker.Disconnect()
}
func Publish(topic string, msg *Message, opts ...PublishOption) error {
return DefaultBroker.Publish(topic, msg, opts...)
}
func Subscribe(topic string, handler Handler, opts ...SubscribeOption) (Subscriber, error) {
return DefaultBroker.Subscribe(topic, handler, opts...)
}
func String() string {
return DefaultBroker.String()
Unsubscribe(context.Context) error
}

View File

@@ -1,47 +0,0 @@
package broker
import (
"github.com/micro/go-micro/registry"
)
var (
// mock data
testData = map[string][]*registry.Service{
"foo": {
{
Name: "foo",
Version: "1.0.0",
Nodes: []*registry.Node{
{
Id: "foo-1.0.0-123",
Address: "localhost:9999",
},
{
Id: "foo-1.0.0-321",
Address: "localhost:9999",
},
},
},
{
Name: "foo",
Version: "1.0.1",
Nodes: []*registry.Node{
{
Id: "foo-1.0.1-321",
Address: "localhost:6666",
},
},
},
{
Name: "foo",
Version: "1.0.3",
Nodes: []*registry.Node{
{
Id: "foo-1.0.3-345",
Address: "localhost:8888",
},
},
},
},
}
)

54
broker/context.go Normal file
View File

@@ -0,0 +1,54 @@
package broker
import (
"context"
)
type brokerKey struct{}
// FromContext returns broker from passed context
func FromContext(ctx context.Context) (Broker, bool) {
if ctx == nil {
return nil, false
}
c, ok := ctx.Value(brokerKey{}).(Broker)
return c, ok
}
// NewContext savess broker in context
func NewContext(ctx context.Context, s Broker) context.Context {
if ctx == nil {
ctx = context.Background()
}
return context.WithValue(ctx, brokerKey{}, s)
}
// SetSubscribeOption returns a function to setup a context with given value
func SetSubscribeOption(k, v interface{}) SubscribeOption {
return func(o *SubscribeOptions) {
if o.Context == nil {
o.Context = context.Background()
}
o.Context = context.WithValue(o.Context, k, v)
}
}
// SetOption returns a function to setup a context with given value
func SetOption(k, v interface{}) Option {
return func(o *Options) {
if o.Context == nil {
o.Context = context.Background()
}
o.Context = context.WithValue(o.Context, k, v)
}
}
// SetPublishOption returns a function to setup a context with given value
func SetPublishOption(k, v interface{}) PublishOption {
return func(o *PublishOptions) {
if o.Context == nil {
o.Context = context.Background()
}
o.Context = context.WithValue(o.Context, k, v)
}
}

View File

@@ -1,11 +0,0 @@
// Package http provides a http based message broker
package http
import (
"github.com/micro/go-micro/broker"
)
// NewBroker returns a new http broker
func NewBroker(opts ...broker.Option) broker.Broker {
return broker.NewBroker(opts...)
}

View File

@@ -1,23 +0,0 @@
package http
import (
"context"
"net/http"
"github.com/micro/go-micro/broker"
)
// Handle registers the handler for the given pattern.
func Handle(pattern string, handler http.Handler) broker.Option {
return func(o *broker.Options) {
if o.Context == nil {
o.Context = context.Background()
}
handlers, ok := o.Context.Value("http_handlers").(map[string]http.Handler)
if !ok {
handlers = make(map[string]http.Handler)
}
handlers[pattern] = handler
o.Context = context.WithValue(o.Context, "http_handlers", handlers)
}
}

View File

@@ -1,704 +0,0 @@
package broker
import (
"bytes"
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net"
"net/http"
"net/url"
"runtime"
"sync"
"time"
"github.com/google/uuid"
"github.com/micro/go-micro/codec/json"
merr "github.com/micro/go-micro/errors"
"github.com/micro/go-micro/registry"
"github.com/micro/go-micro/registry/cache"
maddr "github.com/micro/go-micro/util/addr"
mnet "github.com/micro/go-micro/util/net"
mls "github.com/micro/go-micro/util/tls"
"golang.org/x/net/http2"
)
// HTTP Broker is a point to point async broker
type httpBroker struct {
id string
address string
opts Options
mux *http.ServeMux
c *http.Client
r registry.Registry
sync.RWMutex
subscribers map[string][]*httpSubscriber
running bool
exit chan chan error
// offline message inbox
mtx sync.RWMutex
inbox map[string][][]byte
}
type httpSubscriber struct {
opts SubscribeOptions
id string
topic string
fn Handler
svc *registry.Service
hb *httpBroker
}
type httpEvent struct {
m *Message
t string
}
var (
DefaultSubPath = "/_sub"
broadcastVersion = "ff.http.broadcast"
registerTTL = time.Minute
registerInterval = time.Second * 30
)
func init() {
rand.Seed(time.Now().Unix())
}
func newTransport(config *tls.Config) *http.Transport {
if config == nil {
config = &tls.Config{
InsecureSkipVerify: true,
}
}
dialTLS := func(network string, addr string) (net.Conn, error) {
return tls.Dial(network, addr, config)
}
t := &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).Dial,
TLSHandshakeTimeout: 10 * time.Second,
DialTLS: dialTLS,
}
runtime.SetFinalizer(&t, func(tr **http.Transport) {
(*tr).CloseIdleConnections()
})
// setup http2
http2.ConfigureTransport(t)
return t
}
func newHttpBroker(opts ...Option) Broker {
options := Options{
Codec: json.Marshaler{},
Context: context.TODO(),
}
for _, o := range opts {
o(&options)
}
// set address
addr := ":0"
if len(options.Addrs) > 0 && len(options.Addrs[0]) > 0 {
addr = options.Addrs[0]
}
// get registry
reg, ok := options.Context.Value(registryKey).(registry.Registry)
if !ok {
reg = registry.DefaultRegistry
}
h := &httpBroker{
id: "broker-" + uuid.New().String(),
address: addr,
opts: options,
r: reg,
c: &http.Client{Transport: newTransport(options.TLSConfig)},
subscribers: make(map[string][]*httpSubscriber),
exit: make(chan chan error),
mux: http.NewServeMux(),
inbox: make(map[string][][]byte),
}
// specify the message handler
h.mux.Handle(DefaultSubPath, h)
// get optional handlers
if h.opts.Context != nil {
handlers, ok := h.opts.Context.Value("http_handlers").(map[string]http.Handler)
if ok {
for pattern, handler := range handlers {
h.mux.Handle(pattern, handler)
}
}
}
return h
}
func (h *httpEvent) Ack() error {
return nil
}
func (h *httpEvent) Message() *Message {
return h.m
}
func (h *httpEvent) Topic() string {
return h.t
}
func (h *httpSubscriber) Options() SubscribeOptions {
return h.opts
}
func (h *httpSubscriber) Topic() string {
return h.topic
}
func (h *httpSubscriber) Unsubscribe() error {
return h.hb.unsubscribe(h)
}
func (h *httpBroker) saveMessage(topic string, msg []byte) {
h.mtx.Lock()
defer h.mtx.Unlock()
// get messages
c := h.inbox[topic]
// save message
c = append(c, msg)
// max length 64
if len(c) > 64 {
c = c[:64]
}
// save inbox
h.inbox[topic] = c
}
func (h *httpBroker) getMessage(topic string, num int) [][]byte {
h.mtx.Lock()
defer h.mtx.Unlock()
// get messages
c, ok := h.inbox[topic]
if !ok {
return nil
}
// more message than requests
if len(c) >= num {
msg := c[:num]
h.inbox[topic] = c[num:]
return msg
}
// reset inbox
h.inbox[topic] = nil
// return all messages
return c
}
func (h *httpBroker) subscribe(s *httpSubscriber) error {
h.Lock()
defer h.Unlock()
if err := h.r.Register(s.svc, registry.RegisterTTL(registerTTL)); err != nil {
return err
}
h.subscribers[s.topic] = append(h.subscribers[s.topic], s)
return nil
}
func (h *httpBroker) unsubscribe(s *httpSubscriber) error {
h.Lock()
defer h.Unlock()
var subscribers []*httpSubscriber
// look for subscriber
for _, sub := range h.subscribers[s.topic] {
// deregister and skip forward
if sub.id == s.id {
_ = h.r.Deregister(sub.svc)
continue
}
// keep subscriber
subscribers = append(subscribers, sub)
}
// set subscribers
h.subscribers[s.topic] = subscribers
return nil
}
func (h *httpBroker) run(l net.Listener) {
t := time.NewTicker(registerInterval)
defer t.Stop()
for {
select {
// heartbeat for each subscriber
case <-t.C:
h.RLock()
for _, subs := range h.subscribers {
for _, sub := range subs {
_ = h.r.Register(sub.svc, registry.RegisterTTL(registerTTL))
}
}
h.RUnlock()
// received exit signal
case ch := <-h.exit:
ch <- l.Close()
h.RLock()
for _, subs := range h.subscribers {
for _, sub := range subs {
_ = h.r.Deregister(sub.svc)
}
}
h.RUnlock()
return
}
}
}
func (h *httpBroker) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if req.Method != "POST" {
err := merr.BadRequest("go.micro.broker", "Method not allowed")
http.Error(w, err.Error(), http.StatusMethodNotAllowed)
return
}
defer req.Body.Close()
req.ParseForm()
b, err := ioutil.ReadAll(req.Body)
if err != nil {
errr := merr.InternalServerError("go.micro.broker", "Error reading request body: %v", err)
w.WriteHeader(500)
w.Write([]byte(errr.Error()))
return
}
var m *Message
if err = h.opts.Codec.Unmarshal(b, &m); err != nil {
errr := merr.InternalServerError("go.micro.broker", "Error parsing request body: %v", err)
w.WriteHeader(500)
w.Write([]byte(errr.Error()))
return
}
topic := m.Header[":topic"]
delete(m.Header, ":topic")
if len(topic) == 0 {
errr := merr.InternalServerError("go.micro.broker", "Topic not found")
w.WriteHeader(500)
w.Write([]byte(errr.Error()))
return
}
p := &httpEvent{m: m, t: topic}
id := req.Form.Get("id")
var subs []Handler
h.RLock()
for _, subscriber := range h.subscribers[topic] {
if id != subscriber.id {
continue
}
subs = append(subs, subscriber.fn)
}
h.RUnlock()
// execute the handler
for _, fn := range subs {
fn(p)
}
}
func (h *httpBroker) Address() string {
h.RLock()
defer h.RUnlock()
return h.address
}
func (h *httpBroker) Connect() error {
h.RLock()
if h.running {
h.RUnlock()
return nil
}
h.RUnlock()
h.Lock()
defer h.Unlock()
var l net.Listener
var err error
if h.opts.Secure || h.opts.TLSConfig != nil {
config := h.opts.TLSConfig
fn := func(addr string) (net.Listener, error) {
if config == nil {
hosts := []string{addr}
// check if its a valid host:port
if host, _, err := net.SplitHostPort(addr); err == nil {
if len(host) == 0 {
hosts = maddr.IPs()
} else {
hosts = []string{host}
}
}
// generate a certificate
cert, err := mls.Certificate(hosts...)
if err != nil {
return nil, err
}
config = &tls.Config{Certificates: []tls.Certificate{cert}}
}
return tls.Listen("tcp", addr, config)
}
l, err = mnet.Listen(h.address, fn)
} else {
fn := func(addr string) (net.Listener, error) {
return net.Listen("tcp", addr)
}
l, err = mnet.Listen(h.address, fn)
}
if err != nil {
return err
}
addr := h.address
h.address = l.Addr().String()
go http.Serve(l, h.mux)
go func() {
h.run(l)
h.Lock()
h.opts.Addrs = []string{addr}
h.address = addr
h.Unlock()
}()
// get registry
reg, ok := h.opts.Context.Value(registryKey).(registry.Registry)
if !ok {
reg = registry.DefaultRegistry
}
// set cache
h.r = cache.New(reg)
// set running
h.running = true
return nil
}
func (h *httpBroker) Disconnect() error {
h.RLock()
if !h.running {
h.RUnlock()
return nil
}
h.RUnlock()
h.Lock()
defer h.Unlock()
// stop cache
rc, ok := h.r.(cache.Cache)
if ok {
rc.Stop()
}
// exit and return err
ch := make(chan error)
h.exit <- ch
err := <-ch
// set not running
h.running = false
return err
}
func (h *httpBroker) Init(opts ...Option) error {
h.RLock()
if h.running {
h.RUnlock()
return errors.New("cannot init while connected")
}
h.RUnlock()
h.Lock()
defer h.Unlock()
for _, o := range opts {
o(&h.opts)
}
if len(h.opts.Addrs) > 0 && len(h.opts.Addrs[0]) > 0 {
h.address = h.opts.Addrs[0]
}
if len(h.id) == 0 {
h.id = "broker-" + uuid.New().String()
}
// get registry
reg, ok := h.opts.Context.Value(registryKey).(registry.Registry)
if !ok {
reg = registry.DefaultRegistry
}
// get cache
if rc, ok := h.r.(cache.Cache); ok {
rc.Stop()
}
// set registry
h.r = cache.New(reg)
// reconfigure tls config
if c := h.opts.TLSConfig; c != nil {
h.c = &http.Client{
Transport: newTransport(c),
}
}
return nil
}
func (h *httpBroker) Options() Options {
return h.opts
}
func (h *httpBroker) Publish(topic string, msg *Message, opts ...PublishOption) error {
// create the message first
m := &Message{
Header: make(map[string]string),
Body: msg.Body,
}
for k, v := range msg.Header {
m.Header[k] = v
}
m.Header[":topic"] = topic
// encode the message
b, err := h.opts.Codec.Marshal(m)
if err != nil {
return err
}
// save the message
h.saveMessage(topic, b)
// now attempt to get the service
h.RLock()
s, err := h.r.GetService(topic)
if err != nil {
h.RUnlock()
// ignore error
return nil
}
h.RUnlock()
pub := func(node *registry.Node, t string, b []byte) error {
scheme := "http"
// check if secure is added in metadata
if node.Metadata["secure"] == "true" {
scheme = "https"
}
vals := url.Values{}
vals.Add("id", node.Id)
uri := fmt.Sprintf("%s://%s%s?%s", scheme, node.Address, DefaultSubPath, vals.Encode())
r, err := h.c.Post(uri, "application/json", bytes.NewReader(b))
if err != nil {
return err
}
// discard response body
io.Copy(ioutil.Discard, r.Body)
r.Body.Close()
return nil
}
srv := func(s []*registry.Service, b []byte) {
for _, service := range s {
var nodes []*registry.Node
for _, node := range service.Nodes {
// only use nodes tagged with broker http
if node.Metadata["broker"] != "http" {
continue
}
// look for nodes for the topic
if node.Metadata["topic"] != topic {
continue
}
nodes = append(nodes, node)
}
// only process if we have nodes
if len(nodes) == 0 {
continue
}
switch service.Version {
// broadcast version means broadcast to all nodes
case broadcastVersion:
var success bool
// publish to all nodes
for _, node := range nodes {
// publish async
if err := pub(node, topic, b); err == nil {
success = true
}
}
// save if it failed to publish at least once
if !success {
h.saveMessage(topic, b)
}
default:
// select node to publish to
node := nodes[rand.Int()%len(nodes)]
// publish async to one node
if err := pub(node, topic, b); err != nil {
// if failed save it
h.saveMessage(topic, b)
}
}
}
}
// do the rest async
go func() {
// get a third of the backlog
messages := h.getMessage(topic, 8)
delay := (len(messages) > 1)
// publish all the messages
for _, msg := range messages {
// serialize here
srv(s, msg)
// sending a backlog of messages
if delay {
time.Sleep(time.Millisecond * 100)
}
}
}()
return nil
}
func (h *httpBroker) Subscribe(topic string, handler Handler, opts ...SubscribeOption) (Subscriber, error) {
var err error
var host, port string
options := NewSubscribeOptions(opts...)
// parse address for host, port
host, port, err = net.SplitHostPort(h.Address())
if err != nil {
return nil, err
}
addr, err := maddr.Extract(host)
if err != nil {
return nil, err
}
// create unique id
id := h.id + "." + uuid.New().String()
var secure bool
if h.opts.Secure || h.opts.TLSConfig != nil {
secure = true
}
// register service
node := &registry.Node{
Id: id,
Address: mnet.HostPort(addr, port),
Metadata: map[string]string{
"secure": fmt.Sprintf("%t", secure),
"broker": "http",
"topic": topic,
},
}
// check for queue group or broadcast queue
version := options.Queue
if len(version) == 0 {
version = broadcastVersion
}
service := &registry.Service{
Name: topic,
Version: version,
Nodes: []*registry.Node{node},
}
// generate subscriber
subscriber := &httpSubscriber{
opts: options,
hb: h,
id: id,
topic: topic,
fn: handler,
svc: service,
}
// subscribe now
if err := h.subscribe(subscriber); err != nil {
return nil, err
}
// return the subscriber
return subscriber, nil
}
func (h *httpBroker) String() string {
return "http"
}

View File

@@ -1,351 +0,0 @@
package broker
import (
"sync"
"testing"
"time"
glog "github.com/go-log/log"
"github.com/google/uuid"
"github.com/micro/go-micro/registry/memory"
"github.com/micro/go-micro/util/log"
)
func newTestRegistry() *memory.Registry {
r := memory.NewRegistry()
m := r.(*memory.Registry)
m.Services = testData
return m
}
func sub(be *testing.B, c int) {
// set no op logger
log.SetLogger(glog.DefaultLogger)
be.StopTimer()
m := newTestRegistry()
b := NewBroker(Registry(m))
topic := uuid.New().String()
if err := b.Init(); err != nil {
be.Fatalf("Unexpected init error: %v", err)
}
if err := b.Connect(); err != nil {
be.Fatalf("Unexpected connect error: %v", err)
}
msg := &Message{
Header: map[string]string{
"Content-Type": "application/json",
},
Body: []byte(`{"message": "Hello World"}`),
}
var subs []Subscriber
done := make(chan bool, c)
for i := 0; i < c; i++ {
sub, err := b.Subscribe(topic, func(p Event) error {
done <- true
m := p.Message()
if string(m.Body) != string(msg.Body) {
be.Fatalf("Unexpected msg %s, expected %s", string(m.Body), string(msg.Body))
}
return nil
}, Queue("shared"))
if err != nil {
be.Fatalf("Unexpected subscribe error: %v", err)
}
subs = append(subs, sub)
}
for i := 0; i < be.N; i++ {
be.StartTimer()
if err := b.Publish(topic, msg); err != nil {
be.Fatalf("Unexpected publish error: %v", err)
}
<-done
be.StopTimer()
}
for _, sub := range subs {
sub.Unsubscribe()
}
if err := b.Disconnect(); err != nil {
be.Fatalf("Unexpected disconnect error: %v", err)
}
}
func pub(be *testing.B, c int) {
// set no op logger
log.SetLogger(glog.DefaultLogger)
be.StopTimer()
m := newTestRegistry()
b := NewBroker(Registry(m))
topic := uuid.New().String()
if err := b.Init(); err != nil {
be.Fatalf("Unexpected init error: %v", err)
}
if err := b.Connect(); err != nil {
be.Fatalf("Unexpected connect error: %v", err)
}
msg := &Message{
Header: map[string]string{
"Content-Type": "application/json",
},
Body: []byte(`{"message": "Hello World"}`),
}
done := make(chan bool, c*4)
sub, err := b.Subscribe(topic, func(p Event) error {
done <- true
m := p.Message()
if string(m.Body) != string(msg.Body) {
be.Fatalf("Unexpected msg %s, expected %s", string(m.Body), string(msg.Body))
}
return nil
}, Queue("shared"))
if err != nil {
be.Fatalf("Unexpected subscribe error: %v", err)
}
var wg sync.WaitGroup
ch := make(chan int, c*4)
be.StartTimer()
for i := 0; i < c; i++ {
go func() {
for range ch {
if err := b.Publish(topic, msg); err != nil {
be.Fatalf("Unexpected publish error: %v", err)
}
select {
case <-done:
case <-time.After(time.Second):
}
wg.Done()
}
}()
}
for i := 0; i < be.N; i++ {
wg.Add(1)
ch <- i
}
wg.Wait()
be.StopTimer()
sub.Unsubscribe()
close(ch)
close(done)
if err := b.Disconnect(); err != nil {
be.Fatalf("Unexpected disconnect error: %v", err)
}
}
func TestBroker(t *testing.T) {
m := newTestRegistry()
b := NewBroker(Registry(m))
if err := b.Init(); err != nil {
t.Fatalf("Unexpected init error: %v", err)
}
if err := b.Connect(); err != nil {
t.Fatalf("Unexpected connect error: %v", err)
}
msg := &Message{
Header: map[string]string{
"Content-Type": "application/json",
},
Body: []byte(`{"message": "Hello World"}`),
}
done := make(chan bool)
sub, err := b.Subscribe("test", func(p Event) error {
m := p.Message()
if string(m.Body) != string(msg.Body) {
t.Fatalf("Unexpected msg %s, expected %s", string(m.Body), string(msg.Body))
}
close(done)
return nil
})
if err != nil {
t.Fatalf("Unexpected subscribe error: %v", err)
}
if err := b.Publish("test", msg); err != nil {
t.Fatalf("Unexpected publish error: %v", err)
}
<-done
sub.Unsubscribe()
if err := b.Disconnect(); err != nil {
t.Fatalf("Unexpected disconnect error: %v", err)
}
}
func TestConcurrentSubBroker(t *testing.T) {
m := newTestRegistry()
b := NewBroker(Registry(m))
if err := b.Init(); err != nil {
t.Fatalf("Unexpected init error: %v", err)
}
if err := b.Connect(); err != nil {
t.Fatalf("Unexpected connect error: %v", err)
}
msg := &Message{
Header: map[string]string{
"Content-Type": "application/json",
},
Body: []byte(`{"message": "Hello World"}`),
}
var subs []Subscriber
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
sub, err := b.Subscribe("test", func(p Event) error {
defer wg.Done()
m := p.Message()
if string(m.Body) != string(msg.Body) {
t.Fatalf("Unexpected msg %s, expected %s", string(m.Body), string(msg.Body))
}
return nil
})
if err != nil {
t.Fatalf("Unexpected subscribe error: %v", err)
}
wg.Add(1)
subs = append(subs, sub)
}
if err := b.Publish("test", msg); err != nil {
t.Fatalf("Unexpected publish error: %v", err)
}
wg.Wait()
for _, sub := range subs {
sub.Unsubscribe()
}
if err := b.Disconnect(); err != nil {
t.Fatalf("Unexpected disconnect error: %v", err)
}
}
func TestConcurrentPubBroker(t *testing.T) {
m := newTestRegistry()
b := NewBroker(Registry(m))
if err := b.Init(); err != nil {
t.Fatalf("Unexpected init error: %v", err)
}
if err := b.Connect(); err != nil {
t.Fatalf("Unexpected connect error: %v", err)
}
msg := &Message{
Header: map[string]string{
"Content-Type": "application/json",
},
Body: []byte(`{"message": "Hello World"}`),
}
var wg sync.WaitGroup
sub, err := b.Subscribe("test", func(p Event) error {
defer wg.Done()
m := p.Message()
if string(m.Body) != string(msg.Body) {
t.Fatalf("Unexpected msg %s, expected %s", string(m.Body), string(msg.Body))
}
return nil
})
if err != nil {
t.Fatalf("Unexpected subscribe error: %v", err)
}
for i := 0; i < 10; i++ {
wg.Add(1)
if err := b.Publish("test", msg); err != nil {
t.Fatalf("Unexpected publish error: %v", err)
}
}
wg.Wait()
sub.Unsubscribe()
if err := b.Disconnect(); err != nil {
t.Fatalf("Unexpected disconnect error: %v", err)
}
}
func BenchmarkSub1(b *testing.B) {
sub(b, 1)
}
func BenchmarkSub8(b *testing.B) {
sub(b, 8)
}
func BenchmarkSub32(b *testing.B) {
sub(b, 32)
}
func BenchmarkSub64(b *testing.B) {
sub(b, 64)
}
func BenchmarkSub128(b *testing.B) {
sub(b, 128)
}
func BenchmarkPub1(b *testing.B) {
pub(b, 1)
}
func BenchmarkPub8(b *testing.B) {
pub(b, 8)
}
func BenchmarkPub32(b *testing.B) {
pub(b, 32)
}
func BenchmarkPub64(b *testing.B) {
pub(b, 64)
}
func BenchmarkPub128(b *testing.B) {
pub(b, 128)
}

243
broker/memory.go Normal file
View File

@@ -0,0 +1,243 @@
package broker
import (
"context"
"errors"
"sync"
"github.com/google/uuid"
"github.com/unistack-org/micro/v3/logger"
maddr "github.com/unistack-org/micro/v3/util/addr"
mnet "github.com/unistack-org/micro/v3/util/net"
"github.com/unistack-org/micro/v3/util/rand"
)
type memoryBroker struct {
opts Options
Subscribers map[string][]*memorySubscriber
addr string
sync.RWMutex
connected bool
}
type memoryEvent struct {
opts Options
err error
message interface{}
topic string
}
type memorySubscriber struct {
opts SubscribeOptions
ctx context.Context
exit chan bool
handler Handler
id string
topic string
}
func (m *memoryBroker) Options() Options {
return m.opts
}
func (m *memoryBroker) Address() string {
return m.addr
}
func (m *memoryBroker) Connect(ctx context.Context) error {
m.Lock()
defer m.Unlock()
if m.connected {
return nil
}
// use 127.0.0.1 to avoid scan of all network interfaces
addr, err := maddr.Extract("127.0.0.1")
if err != nil {
return err
}
var rng rand.Rand
i := rng.Intn(20000)
// set addr with port
addr = mnet.HostPort(addr, 10000+i)
m.addr = addr
m.connected = true
return nil
}
func (m *memoryBroker) Disconnect(ctx context.Context) error {
m.Lock()
defer m.Unlock()
if !m.connected {
return nil
}
m.connected = false
return nil
}
func (m *memoryBroker) Init(opts ...Option) error {
for _, o := range opts {
o(&m.opts)
}
return nil
}
func (m *memoryBroker) Publish(ctx context.Context, topic string, msg *Message, opts ...PublishOption) error {
m.RLock()
if !m.connected {
m.RUnlock()
return errors.New("not connected")
}
subs, ok := m.Subscribers[topic]
m.RUnlock()
if !ok {
return nil
}
var v interface{}
if m.opts.Codec != nil {
buf, err := m.opts.Codec.Marshal(msg)
if err != nil {
return err
}
v = buf
} else {
v = msg
}
p := &memoryEvent{
topic: topic,
message: v,
opts: m.opts,
}
eh := m.opts.ErrorHandler
for _, sub := range subs {
if err := sub.handler(p); err != nil {
p.err = err
if sub.opts.ErrorHandler != nil {
eh = sub.opts.ErrorHandler
}
if eh != nil {
eh(p)
} else if m.opts.Logger.V(logger.ErrorLevel) {
m.opts.Logger.Error(m.opts.Context, err.Error())
}
continue
}
}
return nil
}
func (m *memoryBroker) Subscribe(ctx context.Context, topic string, handler Handler, opts ...SubscribeOption) (Subscriber, error) {
m.RLock()
if !m.connected {
m.RUnlock()
return nil, errors.New("not connected")
}
m.RUnlock()
options := NewSubscribeOptions(opts...)
id, err := uuid.NewRandom()
if err != nil {
return nil, err
}
sub := &memorySubscriber{
exit: make(chan bool, 1),
id: id.String(),
topic: topic,
handler: handler,
opts: options,
ctx: ctx,
}
m.Lock()
m.Subscribers[topic] = append(m.Subscribers[topic], sub)
m.Unlock()
go func() {
<-sub.exit
m.Lock()
var newSubscribers []*memorySubscriber
for _, sb := range m.Subscribers[topic] {
if sb.id == sub.id {
continue
}
newSubscribers = append(newSubscribers, sb)
}
m.Subscribers[topic] = newSubscribers
m.Unlock()
}()
return sub, nil
}
func (m *memoryBroker) String() string {
return "memory"
}
func (m *memoryBroker) Name() string {
return m.opts.Name
}
func (m *memoryEvent) Topic() string {
return m.topic
}
func (m *memoryEvent) Message() *Message {
switch v := m.message.(type) {
case *Message:
return v
case []byte:
msg := &Message{}
if err := m.opts.Codec.Unmarshal(v, msg); err != nil {
if m.opts.Logger.V(logger.ErrorLevel) {
m.opts.Logger.Error(m.opts.Context, "[memory]: failed to unmarshal: %v", err)
}
return nil
}
return msg
}
return nil
}
func (m *memoryEvent) Ack() error {
return nil
}
func (m *memoryEvent) Error() error {
return m.err
}
func (m *memorySubscriber) Options() SubscribeOptions {
return m.opts
}
func (m *memorySubscriber) Topic() string {
return m.topic
}
func (m *memorySubscriber) Unsubscribe(ctx context.Context) error {
m.exit <- true
return nil
}
// NewBroker return new memory broker
func NewBroker(opts ...Option) Broker {
return &memoryBroker{
opts: NewOptions(opts...),
Subscribers: make(map[string][]*memorySubscriber),
}
}

View File

@@ -1,197 +0,0 @@
// Package memory provides a memory broker
package memory
import (
"errors"
"math/rand"
"sync"
"time"
"github.com/google/uuid"
"github.com/micro/go-micro/broker"
maddr "github.com/micro/go-micro/util/addr"
mnet "github.com/micro/go-micro/util/net"
)
type memoryBroker struct {
opts broker.Options
addr string
sync.RWMutex
connected bool
Subscribers map[string][]*memorySubscriber
}
type memoryEvent struct {
topic string
message *broker.Message
}
type memorySubscriber struct {
id string
topic string
exit chan bool
handler broker.Handler
opts broker.SubscribeOptions
}
func (m *memoryBroker) Options() broker.Options {
return m.opts
}
func (m *memoryBroker) Address() string {
return m.addr
}
func (m *memoryBroker) Connect() error {
m.Lock()
defer m.Unlock()
if m.connected {
return nil
}
addr, err := maddr.Extract("::")
if err != nil {
return err
}
i := rand.Intn(20000)
// set addr with port
addr = mnet.HostPort(addr, 10000+i)
m.addr = addr
m.connected = true
return nil
}
func (m *memoryBroker) Disconnect() error {
m.Lock()
defer m.Unlock()
if !m.connected {
return nil
}
m.connected = false
return nil
}
func (m *memoryBroker) Init(opts ...broker.Option) error {
for _, o := range opts {
o(&m.opts)
}
return nil
}
func (m *memoryBroker) Publish(topic string, message *broker.Message, opts ...broker.PublishOption) error {
m.RLock()
if !m.connected {
m.RUnlock()
return errors.New("not connected")
}
subs, ok := m.Subscribers[topic]
m.RUnlock()
if !ok {
return nil
}
p := &memoryEvent{
topic: topic,
message: message,
}
for _, sub := range subs {
if err := sub.handler(p); err != nil {
return err
}
}
return nil
}
func (m *memoryBroker) Subscribe(topic string, handler broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) {
m.RLock()
if !m.connected {
m.RUnlock()
return nil, errors.New("not connected")
}
m.RUnlock()
var options broker.SubscribeOptions
for _, o := range opts {
o(&options)
}
sub := &memorySubscriber{
exit: make(chan bool, 1),
id: uuid.New().String(),
topic: topic,
handler: handler,
opts: options,
}
m.Lock()
m.Subscribers[topic] = append(m.Subscribers[topic], sub)
m.Unlock()
go func() {
<-sub.exit
m.Lock()
var newSubscribers []*memorySubscriber
for _, sb := range m.Subscribers[topic] {
if sb.id == sub.id {
continue
}
newSubscribers = append(newSubscribers, sb)
}
m.Subscribers[topic] = newSubscribers
m.Unlock()
}()
return sub, nil
}
func (m *memoryBroker) String() string {
return "memory"
}
func (m *memoryEvent) Topic() string {
return m.topic
}
func (m *memoryEvent) Message() *broker.Message {
return m.message
}
func (m *memoryEvent) Ack() error {
return nil
}
func (m *memorySubscriber) Options() broker.SubscribeOptions {
return m.opts
}
func (m *memorySubscriber) Topic() string {
return m.topic
}
func (m *memorySubscriber) Unsubscribe() error {
m.exit <- true
return nil
}
func NewBroker(opts ...broker.Option) broker.Broker {
var options broker.Options
rand.Seed(time.Now().UnixNano())
for _, o := range opts {
o(&options)
}
return &memoryBroker{
opts: options,
Subscribers: make(map[string][]*memorySubscriber),
}
}

View File

@@ -1,33 +1,33 @@
package memory
package broker
import (
"context"
"fmt"
"testing"
"github.com/micro/go-micro/broker"
)
func TestMemoryBroker(t *testing.T) {
b := NewBroker()
ctx := context.Background()
if err := b.Connect(); err != nil {
if err := b.Connect(ctx); err != nil {
t.Fatalf("Unexpected connect error %v", err)
}
topic := "test"
count := 10
fn := func(p broker.Event) error {
fn := func(p Event) error {
return nil
}
sub, err := b.Subscribe(topic, fn)
sub, err := b.Subscribe(ctx, topic, fn)
if err != nil {
t.Fatalf("Unexpected error subscribing %v", err)
}
for i := 0; i < count; i++ {
message := &broker.Message{
message := &Message{
Header: map[string]string{
"foo": "bar",
"id": fmt.Sprintf("%d", i),
@@ -35,16 +35,16 @@ func TestMemoryBroker(t *testing.T) {
Body: []byte(`hello world`),
}
if err := b.Publish(topic, message); err != nil {
if err := b.Publish(ctx, topic, message); err != nil {
t.Fatalf("Unexpected error publishing %d", i)
}
}
if err := sub.Unsubscribe(); err != nil {
if err := sub.Unsubscribe(ctx); err != nil {
t.Fatalf("Unexpected error unsubscribing from %s: %v", topic, err)
}
if err := b.Disconnect(); err != nil {
if err := b.Disconnect(ctx); err != nil {
t.Fatalf("Unexpected connect error %v", err)
}
}

View File

@@ -1,37 +0,0 @@
package nats
import (
"context"
"github.com/micro/go-micro/broker"
)
// setSubscribeOption returns a function to setup a context with given value
func setSubscribeOption(k, v interface{}) broker.SubscribeOption {
return func(o *broker.SubscribeOptions) {
if o.Context == nil {
o.Context = context.Background()
}
o.Context = context.WithValue(o.Context, k, v)
}
}
// setBrokerOption returns a function to setup a context with given value
func setBrokerOption(k, v interface{}) broker.Option {
return func(o *broker.Options) {
if o.Context == nil {
o.Context = context.Background()
}
o.Context = context.WithValue(o.Context, k, v)
}
}
// setPublishOption returns a function to setup a context with given value
func setPublishOption(k, v interface{}) broker.PublishOption {
return func(o *broker.PublishOptions) {
if o.Context == nil {
o.Context = context.Background()
}
o.Context = context.WithValue(o.Context, k, v)
}
}

View File

@@ -1,255 +0,0 @@
// Package nats provides a NATS broker
package nats
import (
"context"
"errors"
"strings"
"sync"
"github.com/micro/go-micro/broker"
"github.com/micro/go-micro/codec/json"
nats "github.com/nats-io/nats.go"
)
type natsBroker struct {
sync.Once
sync.RWMutex
addrs []string
conn *nats.Conn
opts broker.Options
nopts nats.Options
drain bool
closeCh chan (error)
}
type subscriber struct {
s *nats.Subscription
opts broker.SubscribeOptions
}
type publication struct {
t string
m *broker.Message
}
func (p *publication) Topic() string {
return p.t
}
func (p *publication) Message() *broker.Message {
return p.m
}
func (p *publication) Ack() error {
// nats does not support acking
return nil
}
func (s *subscriber) Options() broker.SubscribeOptions {
return s.opts
}
func (s *subscriber) Topic() string {
return s.s.Subject
}
func (s *subscriber) Unsubscribe() error {
return s.s.Unsubscribe()
}
func (n *natsBroker) Address() string {
if n.conn != nil && n.conn.IsConnected() {
return n.conn.ConnectedUrl()
}
if len(n.addrs) > 0 {
return n.addrs[0]
}
return ""
}
func setAddrs(addrs []string) []string {
var cAddrs []string
for _, addr := range addrs {
if len(addr) == 0 {
continue
}
if !strings.HasPrefix(addr, "nats://") {
addr = "nats://" + addr
}
cAddrs = append(cAddrs, addr)
}
if len(cAddrs) == 0 {
cAddrs = []string{nats.DefaultURL}
}
return cAddrs
}
func (n *natsBroker) Connect() error {
n.Lock()
defer n.Unlock()
status := nats.CLOSED
if n.conn != nil {
status = n.conn.Status()
}
switch status {
case nats.CONNECTED, nats.RECONNECTING, nats.CONNECTING:
return nil
default: // DISCONNECTED or CLOSED or DRAINING
opts := n.nopts
opts.Servers = n.addrs
opts.Secure = n.opts.Secure
opts.TLSConfig = n.opts.TLSConfig
// secure might not be set
if n.opts.TLSConfig != nil {
opts.Secure = true
}
c, err := opts.Connect()
if err != nil {
return err
}
n.conn = c
return nil
}
}
func (n *natsBroker) Disconnect() error {
n.RLock()
defer n.RUnlock()
if n.drain {
n.conn.Drain()
return <-n.closeCh
}
n.conn.Close()
return nil
}
func (n *natsBroker) Init(opts ...broker.Option) error {
n.setOption(opts...)
return nil
}
func (n *natsBroker) Options() broker.Options {
return n.opts
}
func (n *natsBroker) Publish(topic string, msg *broker.Message, opts ...broker.PublishOption) error {
b, err := n.opts.Codec.Marshal(msg)
if err != nil {
return err
}
n.RLock()
defer n.RUnlock()
return n.conn.Publish(topic, b)
}
func (n *natsBroker) Subscribe(topic string, handler broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) {
if n.conn == nil {
return nil, errors.New("not connected")
}
opt := broker.SubscribeOptions{
AutoAck: true,
Context: context.Background(),
}
for _, o := range opts {
o(&opt)
}
fn := func(msg *nats.Msg) {
var m broker.Message
if err := n.opts.Codec.Unmarshal(msg.Data, &m); err != nil {
return
}
handler(&publication{m: &m, t: msg.Subject})
}
var sub *nats.Subscription
var err error
n.RLock()
if len(opt.Queue) > 0 {
sub, err = n.conn.QueueSubscribe(topic, opt.Queue, fn)
} else {
sub, err = n.conn.Subscribe(topic, fn)
}
n.RUnlock()
if err != nil {
return nil, err
}
return &subscriber{s: sub, opts: opt}, nil
}
func (n *natsBroker) String() string {
return "nats"
}
func NewBroker(opts ...broker.Option) broker.Broker {
options := broker.Options{
// Default codec
Codec: json.Marshaler{},
Context: context.Background(),
}
n := &natsBroker{
opts: options,
}
n.setOption(opts...)
return n
}
func (n *natsBroker) setOption(opts ...broker.Option) {
for _, o := range opts {
o(&n.opts)
}
n.Once.Do(func() {
n.nopts = nats.GetDefaultOptions()
})
if nopts, ok := n.opts.Context.Value(optionsKey{}).(nats.Options); ok {
n.nopts = nopts
}
// broker.Options have higher priority than nats.Options
// only if Addrs, Secure or TLSConfig were not set through a broker.Option
// we read them from nats.Option
if len(n.opts.Addrs) == 0 {
n.opts.Addrs = n.nopts.Servers
}
if !n.opts.Secure {
n.opts.Secure = n.nopts.Secure
}
if n.opts.TLSConfig == nil {
n.opts.TLSConfig = n.nopts.TLSConfig
}
n.addrs = setAddrs(n.opts.Addrs)
if n.opts.Context.Value(drainConnectionKey{}) != nil {
n.drain = true
n.closeCh = make(chan error)
n.nopts.ClosedCB = n.onClose
n.nopts.AsyncErrorCB = n.onAsyncError
}
}
func (n *natsBroker) onClose(conn *nats.Conn) {
n.closeCh <- nil
}
func (n *natsBroker) onAsyncError(conn *nats.Conn, sub *nats.Subscription, err error) {
// There are kinds of different async error nats might callback, but we are interested
// in ErrDrainTimeout only here.
if err == nats.ErrDrainTimeout {
n.closeCh <- err
}
}

View File

@@ -1,99 +0,0 @@
package nats
import (
"fmt"
"testing"
"github.com/micro/go-micro/broker"
nats "github.com/nats-io/nats.go"
)
var addrTestCases = []struct {
name string
description string
addrs map[string]string // expected address : set address
}{
{
"brokerOpts",
"set broker addresses through a broker.Option in constructor",
map[string]string{
"nats://192.168.10.1:5222": "192.168.10.1:5222",
"nats://10.20.10.0:4222": "10.20.10.0:4222"},
},
{
"brokerInit",
"set broker addresses through a broker.Option in broker.Init()",
map[string]string{
"nats://192.168.10.1:5222": "192.168.10.1:5222",
"nats://10.20.10.0:4222": "10.20.10.0:4222"},
},
{
"natsOpts",
"set broker addresses through the nats.Option in constructor",
map[string]string{
"nats://192.168.10.1:5222": "192.168.10.1:5222",
"nats://10.20.10.0:4222": "10.20.10.0:4222"},
},
{
"default",
"check if default Address is set correctly",
map[string]string{
"nats://127.0.0.1:4222": "",
},
},
}
// TestInitAddrs tests issue #100. Ensures that if the addrs is set by an option in init it will be used.
func TestInitAddrs(t *testing.T) {
for _, tc := range addrTestCases {
t.Run(fmt.Sprintf("%s: %s", tc.name, tc.description), func(t *testing.T) {
var br broker.Broker
var addrs []string
for _, addr := range tc.addrs {
addrs = append(addrs, addr)
}
switch tc.name {
case "brokerOpts":
// we know that there are just two addrs in the dict
br = NewBroker(broker.Addrs(addrs[0], addrs[1]))
br.Init()
case "brokerInit":
br = NewBroker()
// we know that there are just two addrs in the dict
br.Init(broker.Addrs(addrs[0], addrs[1]))
case "natsOpts":
nopts := nats.GetDefaultOptions()
nopts.Servers = addrs
br = NewBroker(Options(nopts))
br.Init()
case "default":
br = NewBroker()
br.Init()
}
natsBroker, ok := br.(*natsBroker)
if !ok {
t.Fatal("Expected broker to be of types *natsBroker")
}
// check if the same amount of addrs we set has actually been set, default
// have only 1 address nats://127.0.0.1:4222 (current nats code) or
// nats://localhost:4222 (older code version)
if len(natsBroker.addrs) != len(tc.addrs) && tc.name != "default" {
t.Errorf("Expected Addr count = %d, Actual Addr count = %d",
len(natsBroker.addrs), len(tc.addrs))
}
for _, addr := range natsBroker.addrs {
_, ok := tc.addrs[addr]
if !ok {
t.Errorf("Expected '%s' has not been set", addr)
}
}
})
}
}

View File

@@ -1,19 +0,0 @@
package nats
import (
"github.com/micro/go-micro/broker"
nats "github.com/nats-io/nats.go"
)
type optionsKey struct{}
type drainConnectionKey struct{}
// Options accepts nats.Options
func Options(opts nats.Options) broker.Option {
return setBrokerOption(optionsKey{}, opts)
}
// DrainConnection will drain subscription on close
func DrainConnection() broker.Option {
return setBrokerOption(drainConnectionKey{}, struct{}{})
}

View File

@@ -4,60 +4,130 @@ import (
"context"
"crypto/tls"
"github.com/micro/go-micro/codec"
"github.com/micro/go-micro/registry"
"github.com/unistack-org/micro/v3/codec"
"github.com/unistack-org/micro/v3/logger"
"github.com/unistack-org/micro/v3/meter"
"github.com/unistack-org/micro/v3/register"
"github.com/unistack-org/micro/v3/tracer"
)
// Options struct
type Options struct {
Addrs []string
Secure bool
Codec codec.Marshaler
// Tracer used for tracing
Tracer tracer.Tracer
// Register can be used for clustering
Register register.Register
// Codec holds the codec for marshal/unmarshal
Codec codec.Codec
// Logger used for logging
Logger logger.Logger
// Meter used for metrics
Meter meter.Meter
// Context holds external options
Context context.Context
// TLSConfig holds tls.TLSConfig options
TLSConfig *tls.Config
// Other options for implementations of the interface
// can be stored in a context
Context context.Context
// ErrorHandler used when broker can't unmarshal incoming message
ErrorHandler Handler
// Name holds the broker name
Name string
// Addrs holds the broker address
Addrs []string
}
// NewOptions create new Options
func NewOptions(opts ...Option) Options {
options := Options{
Register: register.DefaultRegister,
Logger: logger.DefaultLogger,
Context: context.Background(),
Meter: meter.DefaultMeter,
Codec: codec.DefaultCodec,
Tracer: tracer.DefaultTracer,
}
for _, o := range opts {
o(&options)
}
return options
}
// Context sets the context option
func Context(ctx context.Context) Option {
return func(o *Options) {
o.Context = ctx
}
}
// PublishOptions struct
type PublishOptions struct {
// Other options for implementations of the interface
// can be stored in a context
// Context holds external options
Context context.Context
// BodyOnly flag says the message contains raw body bytes
BodyOnly bool
}
type SubscribeOptions struct {
// AutoAck defaults to true. When a handler returns
// with a nil error the message is acked.
AutoAck bool
// Subscribers with the same queue name
// will create a shared subscription where each
// receives a subset of messages.
Queue string
// Other options for implementations of the interface
// can be stored in a context
Context context.Context
}
type Option func(*Options)
type PublishOption func(*PublishOptions)
type SubscribeOption func(*SubscribeOptions)
var (
registryKey = "github.com/micro/go-micro/registry"
)
func NewSubscribeOptions(opts ...SubscribeOption) SubscribeOptions {
opt := SubscribeOptions{
AutoAck: true,
// NewPublishOptions creates PublishOptions struct
func NewPublishOptions(opts ...PublishOption) PublishOptions {
options := PublishOptions{
Context: context.Background(),
}
for _, o := range opts {
o(&opt)
o(&options)
}
return opt
return options
}
// SubscribeOptions struct
type SubscribeOptions struct {
// Context holds external options
Context context.Context
// ErrorHandler used when broker can't unmarshal incoming message
ErrorHandler Handler
// Group holds consumer group
Group string
// AutoAck flag specifies auto ack of incoming message when no error happens
AutoAck bool
// BodyOnly flag specifies that message contains only body bytes without header
BodyOnly bool
}
// Option func
type Option func(*Options)
// PublishOption func
type PublishOption func(*PublishOptions)
// PublishBodyOnly publish only body of the message
func PublishBodyOnly(b bool) PublishOption {
return func(o *PublishOptions) {
o.BodyOnly = b
}
}
// PublishContext sets the context
func PublishContext(ctx context.Context) PublishOption {
return func(o *PublishOptions) {
o.Context = ctx
}
}
// SubscribeOption func
type SubscribeOption func(*SubscribeOptions)
// NewSubscribeOptions creates new SubscribeOptions
func NewSubscribeOptions(opts ...SubscribeOption) SubscribeOptions {
options := SubscribeOptions{
AutoAck: true,
Context: context.Background(),
}
for _, o := range opts {
o(&options)
}
return options
}
// Addrs sets the host addresses to be used by the broker
@@ -69,47 +139,107 @@ func Addrs(addrs ...string) Option {
// Codec sets the codec used for encoding/decoding used where
// a broker does not support headers
func Codec(c codec.Marshaler) Option {
func Codec(c codec.Codec) Option {
return func(o *Options) {
o.Codec = c
}
}
// DisableAutoAck will disable auto acking of messages
// after they have been handled.
// DisableAutoAck disables auto ack
func DisableAutoAck() SubscribeOption {
return func(o *SubscribeOptions) {
o.AutoAck = false
}
}
// Queue sets the name of the queue to share messages on
// SubscribeAutoAck will disable auto acking of messages
// after they have been handled.
func SubscribeAutoAck(b bool) SubscribeOption {
return func(o *SubscribeOptions) {
o.AutoAck = b
}
}
// SubscribeBodyOnly consumes only body of the message
func SubscribeBodyOnly(b bool) SubscribeOption {
return func(o *SubscribeOptions) {
o.BodyOnly = b
}
}
// ErrorHandler will catch all broker errors that cant be handled
// in normal way, for example Codec errors
func ErrorHandler(h Handler) Option {
return func(o *Options) {
o.ErrorHandler = h
}
}
// SubscribeErrorHandler will catch all broker errors that cant be handled
// in normal way, for example Codec errors
func SubscribeErrorHandler(h Handler) SubscribeOption {
return func(o *SubscribeOptions) {
o.ErrorHandler = h
}
}
// Queue sets the subscribers queue
// Deprecated
func Queue(name string) SubscribeOption {
return func(o *SubscribeOptions) {
o.Queue = name
o.Group = name
}
}
func Registry(r registry.Registry) Option {
// SubscribeGroup sets the name of the queue to share messages on
func SubscribeGroup(name string) SubscribeOption {
return func(o *SubscribeOptions) {
o.Group = name
}
}
// Register sets register option
func Register(r register.Register) Option {
return func(o *Options) {
o.Context = context.WithValue(o.Context, registryKey, r)
o.Register = r
}
}
// Secure communication with the broker
func Secure(b bool) Option {
return func(o *Options) {
o.Secure = b
}
}
// Specify TLS Config
// TLSConfig sets the TLS Config
func TLSConfig(t *tls.Config) Option {
return func(o *Options) {
o.TLSConfig = t
}
}
// Logger sets the logger
func Logger(l logger.Logger) Option {
return func(o *Options) {
o.Logger = l
}
}
// Tracer to be used for tracing
func Tracer(t tracer.Tracer) Option {
return func(o *Options) {
o.Tracer = t
}
}
// Meter sets the meter
func Meter(m meter.Meter) Option {
return func(o *Options) {
o.Meter = m
}
}
// Name sets the name
func Name(n string) Option {
return func(o *Options) {
o.Name = n
}
}
// SubscribeContext set context
func SubscribeContext(ctx context.Context) SubscribeOption {
return func(o *SubscribeOptions) {

View File

@@ -1,66 +0,0 @@
package handler
import (
"context"
"github.com/micro/go-micro/broker"
pb "github.com/micro/go-micro/broker/service/proto"
"github.com/micro/go-micro/errors"
"github.com/micro/go-micro/util/log"
)
type Broker struct {
Broker broker.Broker
}
func (b *Broker) Publish(ctx context.Context, req *pb.PublishRequest, rsp *pb.Empty) error {
log.Debugf("Publishing message to %s topic", req.Topic)
err := b.Broker.Publish(req.Topic, &broker.Message{
Header: req.Message.Header,
Body: req.Message.Body,
})
log.Debugf("Published message to %s topic", req.Topic)
if err != nil {
return errors.InternalServerError("go.micro.broker", err.Error())
}
return nil
}
func (b *Broker) Subscribe(ctx context.Context, req *pb.SubscribeRequest, stream pb.Broker_SubscribeStream) error {
errChan := make(chan error, 1)
// message handler to stream back messages from broker
handler := func(p broker.Event) error {
if err := stream.Send(&pb.Message{
Header: p.Message().Header,
Body: p.Message().Body,
}); err != nil {
select {
case errChan <- err:
return err
default:
return err
}
}
return nil
}
log.Debugf("Subscribing to %s topic", req.Topic)
sub, err := b.Broker.Subscribe(req.Topic, handler, broker.Queue(req.Queue))
if err != nil {
return errors.InternalServerError("go.micro.broker", err.Error())
}
defer func() {
log.Debugf("Unsubscribing from topic %s", req.Topic)
sub.Unsubscribe()
}()
select {
case <-ctx.Done():
log.Debugf("Context done for subscription to topic %s", req.Topic)
return nil
case err := <-errChan:
log.Debugf("Subscription error for topic %s: %v", req.Topic, err)
return err
}
}

View File

@@ -1,173 +0,0 @@
// Code generated by protoc-gen-micro. DO NOT EDIT.
// source: github.com/micro/go-micro/broker/proto/broker.proto
package go_micro_broker
import (
fmt "fmt"
proto "github.com/golang/protobuf/proto"
math "math"
)
import (
context "context"
client "github.com/micro/go-micro/client"
server "github.com/micro/go-micro/server"
)
// 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.ProtoPackageIsVersion3 // please upgrade the proto package
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ client.Option
var _ server.Option
// Client API for Broker service
type BrokerService interface {
Publish(ctx context.Context, in *PublishRequest, opts ...client.CallOption) (*Empty, error)
Subscribe(ctx context.Context, in *SubscribeRequest, opts ...client.CallOption) (Broker_SubscribeService, error)
}
type brokerService struct {
c client.Client
name string
}
func NewBrokerService(name string, c client.Client) BrokerService {
if c == nil {
c = client.NewClient()
}
if len(name) == 0 {
name = "go.micro.broker"
}
return &brokerService{
c: c,
name: name,
}
}
func (c *brokerService) Publish(ctx context.Context, in *PublishRequest, opts ...client.CallOption) (*Empty, error) {
req := c.c.NewRequest(c.name, "Broker.Publish", in)
out := new(Empty)
err := c.c.Call(ctx, req, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *brokerService) Subscribe(ctx context.Context, in *SubscribeRequest, opts ...client.CallOption) (Broker_SubscribeService, error) {
req := c.c.NewRequest(c.name, "Broker.Subscribe", &SubscribeRequest{})
stream, err := c.c.Stream(ctx, req, opts...)
if err != nil {
return nil, err
}
if err := stream.Send(in); err != nil {
return nil, err
}
return &brokerServiceSubscribe{stream}, nil
}
type Broker_SubscribeService interface {
SendMsg(interface{}) error
RecvMsg(interface{}) error
Close() error
Recv() (*Message, error)
}
type brokerServiceSubscribe struct {
stream client.Stream
}
func (x *brokerServiceSubscribe) Close() error {
return x.stream.Close()
}
func (x *brokerServiceSubscribe) SendMsg(m interface{}) error {
return x.stream.Send(m)
}
func (x *brokerServiceSubscribe) RecvMsg(m interface{}) error {
return x.stream.Recv(m)
}
func (x *brokerServiceSubscribe) Recv() (*Message, error) {
m := new(Message)
err := x.stream.Recv(m)
if err != nil {
return nil, err
}
return m, nil
}
// Server API for Broker service
type BrokerHandler interface {
Publish(context.Context, *PublishRequest, *Empty) error
Subscribe(context.Context, *SubscribeRequest, Broker_SubscribeStream) error
}
func RegisterBrokerHandler(s server.Server, hdlr BrokerHandler, opts ...server.HandlerOption) error {
type broker interface {
Publish(ctx context.Context, in *PublishRequest, out *Empty) error
Subscribe(ctx context.Context, stream server.Stream) error
}
type Broker struct {
broker
}
h := &brokerHandler{hdlr}
return s.Handle(s.NewHandler(&Broker{h}, opts...))
}
type brokerHandler struct {
BrokerHandler
}
func (h *brokerHandler) Publish(ctx context.Context, in *PublishRequest, out *Empty) error {
return h.BrokerHandler.Publish(ctx, in, out)
}
func (h *brokerHandler) Subscribe(ctx context.Context, stream server.Stream) error {
m := new(SubscribeRequest)
if err := stream.Recv(m); err != nil {
return err
}
return h.BrokerHandler.Subscribe(ctx, m, &brokerSubscribeStream{stream})
}
type Broker_SubscribeStream interface {
SendMsg(interface{}) error
RecvMsg(interface{}) error
Close() error
Send(*Message) error
}
type brokerSubscribeStream struct {
stream server.Stream
}
func (x *brokerSubscribeStream) Close() error {
return x.stream.Close()
}
func (x *brokerSubscribeStream) SendMsg(m interface{}) error {
return x.stream.Send(m)
}
func (x *brokerSubscribeStream) RecvMsg(m interface{}) error {
return x.stream.Recv(m)
}
func (x *brokerSubscribeStream) Send(m *Message) error {
return x.stream.Send(m)
}

Some files were not shown because too many files have changed in this diff Show More