Compare commits

..

356 Commits

Author SHA1 Message Date
Asim Aslam
89fc142e47 Update to use mdns 0.2.0 2019-07-31 13:16:57 +01:00
Asim Aslam
0b2c8ee523 Add top level data package comment 2019-07-30 16:47:18 +01:00
Asim Aslam
852abcaaed yolo commit functioning router code. all credit to the milos gajdos 2019-07-29 18:57:40 +01:00
Asim Aslam
11f80708ce move lock 2019-07-29 12:52:52 +01:00
Asim Aslam
104778e5e5 move lock 2019-07-29 12:52:32 +01:00
Asim Aslam
ae99b9a887 syntactic changes 2019-07-29 12:44:59 +01:00
Asim Aslam
8fdc050e2e syntactic changes 2019-07-29 12:44:28 +01:00
Asim Aslam
8855beb62d syntactic changes 2019-07-29 12:43:20 +01:00
Asim Aslam
47acdf6a4b move Table to table 2019-07-29 12:40:13 +01:00
Asim Aslam
4fc9b9821a Merge pull request #621 from milosgajdos83/no-table-package
[WIP] No table package. router/service package introduced
2019-07-29 12:36:40 +01:00
Asim Aslam
a5fb124b22 update the mdns version 2019-07-29 12:34:00 +01:00
Asim Aslam
5b327ce723 change id to name in resolver 2019-07-28 20:00:09 +01:00
Asim Aslam
2b5bf1154a rename config tests 2019-07-28 19:52:01 +01:00
Asim Aslam
b7b8f8bf11 remove agent readme 2019-07-28 19:47:25 +01:00
Asim Aslam
a63dcda003 Strip the verbosity of the debug handler 2019-07-28 19:43:50 +01:00
Asim Aslam
1db98ee0f0 move all the buffer references to util/buf 2019-07-28 19:33:24 +01:00
Asim Aslam
f2669e7b1e Move connection pool to own package 2019-07-28 18:56:18 +01:00
Asim Aslam
adb6760e21 readd the resolver 2019-07-28 12:14:40 +01:00
Asim Aslam
2b3a87a212 Merge pull request #617 from three-zhang/master
fix bug
2019-07-27 18:08:32 +01:00
Milos Gajdos
3d2ec5dbb1 Regenerated proto because proto reasons. 2019-07-27 16:12:44 +01:00
Milos Gajdos
96f9ce1bd3 Proper router stopping. Printable router status. 2019-07-27 16:11:06 +01:00
Milos Gajdos
cb3052ce04 Proper stopping of service router 2019-07-27 16:11:06 +01:00
Milos Gajdos
2f1658c213 Table package is no more, hence removed references to it 2019-07-27 16:11:06 +01:00
Milos Gajdos
d8b00e801d Stop watcher when router stops. Drain advert channel when stopping. 2019-07-27 16:11:06 +01:00
Milos Gajdos
002abca61f Finished Advertise(). Implemented Process() 2019-07-27 16:11:06 +01:00
Milos Gajdos
c5740ae031 Outline of Advertise, Watch and start of the router. 2019-07-27 16:11:05 +01:00
Milos Gajdos
ddad43bd77 Added service.Router Route CRUD. Outlined watcher and run() 2019-07-27 16:11:05 +01:00
Milos Gajdos
b6fb969ab9 Add List and Lookup implementation. Default error for not implement. 2019-07-27 16:11:05 +01:00
Milos Gajdos
22d0f1f08f Changed documentation. 2019-07-27 16:08:14 +01:00
Milos Gajdos
c3a8146d99 Added outline of router/service package. 2019-07-27 16:08:14 +01:00
Milos Gajdos
2338780a61 Full router RPC coverage 2019-07-27 16:08:14 +01:00
Milos Gajdos
e22c4b4c07 table package is no more. Cleaned up unnecessary code, too. 2019-07-27 16:04:08 +01:00
张三
100cb9db6b fix bug
https://github.com/micro/micro/issues/293
Send request failed using micro Content-Type application/grpc+json
2019-07-27 11:11:16 +08:00
Asim Aslam
4e27aac398 regen router proto 2019-07-26 18:07:36 -07:00
Asim Aslam
7ca06f0c1d set router proto package name to go.micro.router 2019-07-26 18:07:14 -07:00
Asim Aslam
7ca8f8f0ab Merge pull request #611 from milosgajdos83/rpc-router
Adds new RPC methods to router service interface
2019-07-24 13:30:29 -07:00
Milos Gajdos
9ad5ae6644 Adds new RPC methods to router service interface
We have added Advertise() and Process() RPCs in this commit.
2019-07-24 21:07:04 +01:00
Asim Aslam
220a8fafb1 Merge pull request #610 from milosgajdos83/proxy-watch
Adds route watcher to mucp.Proxy
2019-07-24 11:19:52 -07:00
Milos Gajdos
809de7a052 Mutex Unlock when we fail to store route in cache. 2019-07-24 19:13:05 +01:00
Milos Gajdos
23f0231a09 Adds route watcher to mucp.Proxy 2019-07-24 19:03:13 +01:00
Asim Aslam
74cbce72df Merge pull request #609 from milosgajdos83/proxy-router-interface
mucp Proxy no longer uses RPC interface of router.Router directly
2019-07-24 10:40:33 -07:00
Milos Gajdos
b55adc0c30 mucp Proxy no longer uses RPC interface of router.Router directly 2019-07-24 18:32:39 +01:00
Asim Aslam
388ac34b7c Merge pull request #608 from milosgajdos83/router-cleanup
Small router refactoring
2019-07-24 09:46:48 -07:00
Milos Gajdos
13a8cfe7f3 Small function documentation update 2019-07-24 17:22:27 +01:00
Milos Gajdos
1e94d9fe5a Router cleanup and refactoring for win and profit.
This commit adds the following changes to router package:
* it refactors Advertise() function which now does only what
it claims to do: advertising
* various router packages functions/methods have been renamed to make
their functionality more obvious and more in line with what they actually do
* function documentation changes related to the above bullet points
2019-07-24 17:16:52 +01:00
Asim Aslam
49dcc3d1bd Remove readme and examples from web repo 2019-07-22 09:57:34 -07:00
Milos Gajdos
481ebe9d4f Merge pull request #604 from BruceWangNo1/patch-1
Update client.go
2019-07-22 10:55:55 +01:00
Bruce Wang
502f6d3e9f Update client.go
fixed one typo
2019-07-22 15:41:14 +08:00
Asim Aslam
8f2585724c Merge pull request #598 from unistack-org/ipv6fix
bunch of other ipv6 fixes
2019-07-18 07:24:47 -07:00
1217ca94b1 bunch of other ipv6 fixes
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2019-07-18 08:59:53 +03:00
Asim Aslam
96cf14ed53 Merge pull request #591 from milosgajdos83/advert-damp
[WIP] Fixes advert route event dampening behaviour
2019-07-17 08:12:35 -07:00
Asim Aslam
3a8edd705c Merge pull request #594 from unistack-org/ipv6
fix ipv6 addr parsing
2019-07-17 07:51:17 -07:00
Milos Gajdos
94b6455577 Increment WaitGroup before launching advertiseEvents goroutine 2019-07-17 13:02:47 +01:00
e688ab0a45 fix ipv6 addr parsing and using
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2019-07-17 12:20:29 +03:00
Milos Gajdos
2803146673 Renaming rampage
Addressing the comments in #591, router.String() now returns "default"

Furthermore, a tonne of other renaming has been included in this commit
as a result of running go vet ./... inside the router package.
2019-07-17 00:06:11 +01:00
Asim Aslam
d4fefc4b76 Merge pull request #592 from unistack-org/speedup
changes to minimize allocations and provide useful info
2019-07-16 14:41:11 -07:00
a3bddf5839 changes to minimize allocations and provide useful info
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2019-07-17 00:21:03 +03:00
Milos Gajdos
92495d22db Fixes advert dampening behaviour.
This commit adds the following changes:
* advert now stores a list of route events as opposed to just last one
* attempt to dedup route events before appending them to advert
* have max suppress threshold for long time suppressed adverts
* decaying events on every advert tick

Originally we werent decaying penalties on every advert tick.
That was incorrect behaviour. Furthermore some events would end up being
accumulated potentially causing memory leaks.

We were also overriding the last received router event which was causing
incorrect sequence of events to be applied when received by a receiver:
Create, Delete would be "squashed" into Delete only which would be
nonsensical since the Create event would never be delivered hence we
would be deleting nonexistent routes.

Not Decaying the events on every tick or not having the max suppression
threshold could lead to DoS by growing the router memory infinitely.
2019-07-16 19:00:25 +01:00
Asim Aslam
8c7e35c3c6 Merge pull request #587 from milosgajdos83/registry-copy-perf
Preallocate slices in registry.Copy() to avoid append() reallocations when copying data
2019-07-15 07:04:49 -07:00
Milos Gajdos
c108188d65 Preallocate nodes slice in addNodes before populating it 2019-07-15 14:47:33 +01:00
Milos Gajdos
609934ce99 Preallocate slices; avoide append() reallocations when copying data 2019-07-15 11:13:58 +01:00
Asim Aslam
aa79c41fc5 update tunnel comment 2019-07-14 18:34:32 -07:00
Asim Aslam
a549f92dec Merge pull request #585 from unistack-org/transport2
transport memory: fix races
2019-07-13 19:38:22 -07:00
81d2259fac transport memory: fix races
* fix race with rand.Intn for non default source
* increase random interval to avoid issues when many services
  running on the host

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2019-07-13 23:47:57 +03:00
Asim Aslam
2fecde1dbb Merge pull request #583 from unistack-org/broker
broker memory: fix issue with publish/subscribe
2019-07-13 00:16:28 +01:00
008749b2b0 broker memory: fix issue with publish/subscribe
mutex locking have errors, so when two service (one pub, other sub)
try to use this broker it waits for mutex release and nothing works

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2019-07-13 00:04:53 +03:00
Asim Aslam
3ccb900bca Merge pull request #582 from unistack-org/memory2
memory transport: use write mutex lock when close
2019-07-12 10:29:46 +01:00
a72e1185da memory transport: use write mutex lock when close
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2019-07-12 12:11:08 +03:00
Asim Aslam
5157241c88 Merge branch 'master' of ssh://github.com/micro/go-micro 2019-07-11 21:46:33 +01:00
Asim Aslam
70d811c47a don't use quic in the test 2019-07-11 21:46:27 +01:00
Asim Aslam
b371704444 Merge pull request #581 from milosgajdos83/proto-update
Added proto.Advert, proto.TableEvent is now proto.Event
2019-07-11 21:44:10 +01:00
Asim Aslam
a5f21e69ad Merge branch 'master' of ssh://github.com/micro/go-micro 2019-07-11 21:41:00 +01:00
Asim Aslam
6b984136f7 update go mod 2019-07-11 21:40:52 +01:00
Milos Gajdos
9c851f297b Added proto.Advert type to protobuf definitions 2019-07-11 21:14:34 +01:00
Asim Aslam
dac8a13a77 Merge pull request #580 from milosgajdos83/advertise-table
Advertise full table every minute.
2019-07-11 12:49:02 +01:00
Asim Aslam
360e193a01 update go mod 2019-07-11 12:47:50 +01:00
Milos Gajdos
35a1de91a9 Advertise full table every minute. 2019-07-11 12:39:20 +01:00
Asim Aslam
7631463b94 fix compilation errors 2019-07-11 10:47:02 +01:00
Asim Aslam
6581586226 Make tunnel test use quic 2019-07-11 10:34:01 +01:00
Asim Aslam
06c29302d7 Merge branch 'master' of ssh://github.com/micro/go-micro 2019-07-11 09:38:27 +01:00
Asim Aslam
dab0e9e9bc Set next protos in quic 2019-07-11 09:38:20 +01:00
Asim Aslam
47d91a1f64 Merge pull request #579 from magodo/magodo/store_get_reset_expiry
`memoryStore.Read()` returns honor `Record.Expiry`
2019-07-11 08:39:46 +01:00
magodo
bdeae91063 condense code 2019-07-11 14:13:58 +08:00
magodo
c8d57032bc update expiry only if it is non-zero 2019-07-11 12:58:20 +08:00
magodo
3abe3aa28b store.Read() returns honor Record.Expiry 2019-07-11 12:51:55 +08:00
Asim Aslam
9b1cb4ef0e functioning tunnel with test 2019-07-11 00:55:50 +01:00
Asim Aslam
b4796724d9 Merge branch 'master' of ssh://github.com/micro/go-micro 2019-07-11 00:14:43 +01:00
Asim Aslam
ae5376cc0e functioning tunnel/link code 2019-07-11 00:14:36 +01:00
Asim Aslam
7bee0629c2 Merge pull request #578 from unistack-org/memory
memory transport: fix race cond on channel close
2019-07-10 23:30:46 +01:00
29fa8de98e memory transport: fix race cond on channel close
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2019-07-11 01:21:03 +03:00
Asim Aslam
382fbecd40 Merge pull request #577 from milosgajdos83/update-events
Added update action to handle update registry events. Table.Update inserts when no route found.
2019-07-10 21:54:48 +01:00
Milos Gajdos
a0ee7d2092 Added update action to manageServiceRoutes. Table is embedded; skip opts 2019-07-10 21:28:32 +01:00
Asim Aslam
1f744b31a4 Return the dead node when deleting the service 2019-07-10 21:03:53 +01:00
Asim Aslam
998a23c963 Functional code for link 2019-07-10 20:04:01 +01:00
Asim Aslam
e17ecf66b1 Fix breaking code 2019-07-10 20:03:55 +01:00
Asim Aslam
c5dd737568 Add back in broker address 2019-07-10 19:58:30 +01:00
Asim Aslam
7c29be288b Update a tunnel top level comment 2019-07-10 19:33:34 +01:00
Asim Aslam
217f540601 The listener has no session id 2019-07-10 19:17:36 +01:00
Asim Aslam
ffae0f0fab Add a comment for tunnel processor 2019-07-10 19:13:50 +01:00
Asim Aslam
4cca2b43a3 Add further link comments 2019-07-10 19:11:32 +01:00
Asim Aslam
8c157c1d5f update link comments 2019-07-10 19:09:22 +01:00
Asim Aslam
1f218f7b48 Allow the socket to be specified 2019-07-10 19:07:18 +01:00
Asim Aslam
7e0d4fe0cf Merge branch 'master' of ssh://github.com/micro/go-micro 2019-07-10 19:01:38 +01:00
Asim Aslam
0a39fe39c3 Update tunnel to use id+session for the key 2019-07-10 19:01:24 +01:00
Milos Gajdos
163b917ec7 proto.EventType Insert is now Create to mirror table.Event 2019-07-10 18:37:46 +01:00
Asim Aslam
0f16eb2858 add further comments to tunnel 2019-07-10 18:35:10 +01:00
Asim Aslam
89231f701b Add comments and session 2019-07-10 18:26:11 +01:00
Asim Aslam
196e76e350 Merge branch 'master' of ssh://github.com/micro/go-micro 2019-07-10 18:24:12 +01:00
Asim Aslam
f3d9177233 Add sessions to tunnel 2019-07-10 18:24:03 +01:00
Asim Aslam
8b7ac8a3f9 Merge pull request #576 from milosgajdos83/router-rpc
Added List and Watch rpc calls.
2019-07-10 17:55:23 +01:00
Milos Gajdos
8f5aed707e Table.Add is now Table.Create. Insesrt event is now Create event. 2019-07-10 17:46:22 +01:00
Asim Aslam
c71576a538 Update link Id comment 2019-07-10 17:43:36 +01:00
Asim Aslam
27cfc06828 Cleanup and move around the link code 2019-07-10 17:42:41 +01:00
Asim Aslam
717ba4b3c0 Add tunnel comments 2019-07-10 17:41:17 +01:00
Asim Aslam
4e3a230356 top level package comment 2019-07-10 17:40:14 +01:00
Asim Aslam
66c2519696 Add Tunnel: an interface for stream duplexing over a link 2019-07-10 17:36:04 +01:00
Milos Gajdos
86dfa82dfa Added List and Watch rpc calls. 2019-07-10 17:21:55 +01:00
Asim Aslam
55f8045a70 Add link: a layer ontop of a transport socket 2019-07-10 17:12:51 +01:00
Asim Aslam
b23d955536 Use gateway if available 2019-07-10 08:26:33 +01:00
Asim Aslam
5b565f9f10 update comment 2019-07-10 07:56:52 +01:00
Asim Aslam
9955ed2034 move table 2019-07-10 07:56:18 +01:00
Asim Aslam
c36107e811 cleanup consts 2019-07-10 07:51:24 +01:00
Asim Aslam
a08b64c8ab remove the string methods 2019-07-10 07:50:33 +01:00
Asim Aslam
64ec0633a3 Fix breaks and go fmt 2019-07-10 07:47:17 +01:00
Asim Aslam
0a1b657221 visual cleanup of router code 2019-07-10 07:45:27 +01:00
Asim Aslam
34967e8e33 Merge pull request #573 from milosgajdos83/flap-detection
Router rework. Flap detection. Table package.
2019-07-10 07:12:18 +01:00
Asim Aslam
eda380284c remove network 2019-07-09 18:45:14 +01:00
Asim Aslam
0bf54c122f move transport back 2019-07-09 18:41:26 +01:00
Asim Aslam
97282a5377 remove resolver 2019-07-09 16:54:44 +01:00
Asim Aslam
b642d5e1c0 remove proto dir 2019-07-09 16:53:30 +01:00
Asim Aslam
c5a282ddd3 remove the tunnel 2019-07-09 16:52:44 +01:00
Milos Gajdos
6cf8bde612 Router selector and proxy modifications due to Route struct changes. 2019-07-09 16:45:31 +01:00
Asim Aslam
327029beff fix string method 2019-07-09 16:44:43 +01:00
Asim Aslam
c5214c931f reorder and reword 2019-07-09 16:38:44 +01:00
Asim Aslam
d725980444 add some initialisers 2019-07-09 16:37:59 +01:00
Milos Gajdos
23cb811f60 Removed fmt.Stringer artistry from all roouter and table structs 2019-07-09 16:17:18 +01:00
Milos Gajdos
c5fb409760 Removed debug logs 2019-07-09 15:55:39 +01:00
Milos Gajdos
70665e5a7d Route has changed to accomodate Link, Service and Address 2019-07-09 15:46:32 +01:00
Milos Gajdos
449aa0a339 Collect ANNOUNCE mesage events before adding default gateway. 2019-07-09 15:46:31 +01:00
Milos Gajdos
265271008e Simplified processEvents loop; Added router Announcement. 2019-07-09 15:46:31 +01:00
Milos Gajdos
b82245429e Simplified table logic. Lookup tests. mucp/cient update 2019-07-09 15:46:31 +01:00
Milos Gajdos
cc590f5f2c Table now has a dedicated package inside router package. 2019-07-09 15:46:31 +01:00
Milos Gajdos
0c1a28a9b6 Router routing table management. Table route hashes. Status codes changed.
We now manage routing table actions using dedicated functions run on
either registry or services in the registry.

Routing table now uses Route.Hash() instead of maintaining its own hash
struct filed which previously performed these operations.

Various names of variables have been changed to make them more concise.
2019-07-09 15:46:31 +01:00
Milos Gajdos
30d05e34a9 Read and remove routes based on registry event deltas 2019-07-09 15:46:31 +01:00
Milos Gajdos
b68f0e237f Removed event from eventMap once sent to be advertised 2019-07-09 15:46:31 +01:00
Milos Gajdos
72ef032162 First shot at flapping detection and event advertising.
This commit also adds Route hash function, lots of debug messages for
now and String() methods for various API objects.
2019-07-09 15:46:30 +01:00
Milos Gajdos
d6c07dfb16 Update is now Advert 2019-07-09 15:46:30 +01:00
Milos Gajdos
ea872f6900 Updated error statements; Update ships list of events. 2019-07-09 15:46:30 +01:00
Asim Aslam
6bdc23a3aa add comments 2019-07-08 16:32:12 +01:00
Asim Aslam
fa54db5ba5 rename network name to go.micro 2019-07-08 16:27:02 +01:00
Asim Aslam
8015a1daaf Merge branch 'master' of ssh://github.com/micro/go-micro 2019-07-08 16:25:41 +01:00
Asim Aslam
608a1f8add remove node code 2019-07-08 16:25:04 +01:00
Asim Aslam
4a02e1ff2f rewrite network interface 2019-07-08 16:24:57 +01:00
Asim Aslam
5cd1e81ba9 Merge pull request #570 from sunfuze/grpc-json-marshal
grpc: using jsonpb.Marshaler to do Marshal, map to jsonpb.Unmarsh
2019-07-08 08:44:51 +01:00
Asim Aslam
d3edad474e Merge pull request #571 from micro/remove-port
Remove Port from registry
2019-07-08 08:18:26 +01:00
Asim Aslam
e0bf1c2283 Remove Port from registry 2019-07-08 08:01:42 +01:00
Joe
b655f7f55a grpc: using jsonpb.Marshaler to do Marshal, map to jsonpb.Unmarsh 2019-07-08 10:32:10 +08:00
Asim Aslam
5b7454e5a8 update transport package comments 2019-07-07 15:04:07 +01:00
Asim Aslam
0b732b2c49 update transport package comments 2019-07-07 15:03:08 +01:00
Asim Aslam
be33d9204a Merge pull request #569 from micro/event
Change Publication to Event
2019-07-07 12:45:37 +01:00
Asim Aslam
4b4ad68eb9 Change Publication to Event 2019-07-07 12:44:09 +01:00
Asim Aslam
79b03a6825 add broker args 2019-07-07 12:36:14 +01:00
Asim Aslam
777a203f96 gofmt 2019-07-07 12:33:54 +01:00
Asim Aslam
c1097a4509 strip broker address 2019-07-07 12:33:47 +01:00
Asim Aslam
5f664faeba Add transport options comments 2019-07-07 12:23:03 +01:00
Asim Aslam
d2d6841f02 Move transport to network/transport 2019-07-07 10:37:34 +01:00
Asim Aslam
eafc930f84 Change network id to name 2019-07-07 10:10:38 +01:00
Asim Aslam
d1fc3c361e Merge pull request #566 from unistack-org/speed
codec grpc: fix extra allocations on message unmarshal
2019-07-04 17:29:32 +01:00
e40307c567 codec grpc: fix extra allocations on message unmarshal
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2019-07-04 14:06:29 +03:00
Asim Aslam
a412486c39 Update registry util semantics 2019-07-04 11:36:49 +01:00
Asim Aslam
59a0e727e4 Merge pull request #563 from unistack-org/race
export registry util function to safe copy registry data
2019-07-04 11:16:54 +01:00
Asim Aslam
b35f227f7a Merge pull request #565 from sunfuze/grpc-json-unmarshal
grpc: if unmarshal target is proto.Message, using jsonpb
2019-07-04 11:16:11 +01:00
Asim Aslam
00ba1655ca remove some readmes 2019-07-04 11:15:54 +01:00
Joe
e88041dc26 if unmarshal target is proto.Message, using jsonpb 2019-07-04 16:43:36 +08:00
0e34c572b4 export registry util function to safe copy registry data
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2019-07-04 11:39:43 +03:00
Asim Aslam
2644497ccb Fix some link connection logic 2019-07-03 19:51:40 +01:00
Asim Aslam
e54de56376 Functional loopback code 2019-07-03 19:26:24 +01:00
Asim Aslam
7008809eff Make the link use debug 2019-07-02 20:57:23 +01:00
Asim Aslam
f619e46def Some functioning network code 2019-07-02 20:54:21 +01:00
Asim Aslam
c3611aead2 go fmt 2019-07-02 20:53:42 +01:00
Asim Aslam
686aa3aa05 log levels 2019-07-02 19:21:43 +01:00
Asim Aslam
543dc0166c Restructure network things before moving 2019-07-02 08:45:00 +01:00
Asim Aslam
372ad949ff Rename to mucp transport 2019-07-02 00:48:15 +01:00
Asim Aslam
a0c2d18c40 Merge pull request #559 from milosgajdos83/table-tests
Default routing table tests
2019-07-02 00:28:52 +01:00
Asim Aslam
b4236f4430 Add network transport 2019-07-02 00:27:53 +01:00
Milos Gajdos
0e1fcc4f28 Stop hardcoding table sizes; increment as you move on. 2019-07-01 23:38:49 +01:00
Milos Gajdos
8f22e61a8b List test function properly named. 2019-07-01 23:38:48 +01:00
Milos Gajdos
956902f641 Added List tests. 2019-07-01 23:38:48 +01:00
Milos Gajdos
ffac0b9a18 First batch of Add/Del/Update tests. 2019-07-01 23:38:48 +01:00
Asim Aslam
c108b51d2a add network to Node proto 2019-07-01 23:12:05 +01:00
Asim Aslam
5fd798c9b6 add resolver comment 2019-07-01 23:11:55 +01:00
Asim Aslam
ebe3633082 move network initialiser code 2019-07-01 22:59:11 +01:00
Asim Aslam
032c3134c6 update comment 2019-07-01 22:54:26 +01:00
Asim Aslam
8ccf61ebaf Strip Link methods 2019-07-01 22:52:28 +01:00
Asim Aslam
fbbc33d0f9 Set Network() to string 2019-07-01 22:41:27 +01:00
Milos Gajdos
da299ea26b Simmplified RT Lookup. No more Metric in Query. 2019-07-01 20:33:08 +01:00
Asim Aslam
d3e200575c Merge branch 'master' of ssh://github.com/micro/go-micro 2019-07-01 18:37:45 +01:00
Asim Aslam
ddee8412ff Add tunnel interface 2019-07-01 18:37:39 +01:00
Asim Aslam
c84f101e17 Merge pull request #553 from milosgajdos83/router-network
Changed router interface. Added table watcher. Advertise routes
2019-07-01 16:17:02 +01:00
Milos Gajdos
f6e064cdbd Fixed router idempotency. Return registry.ErrWatchStopped from mdns reg 2019-07-01 15:46:26 +01:00
Milos Gajdos
cff46c3fd8 Added Init state. Recreate exit and advertise channels when recovering
In order to differentiate between intialized and other states we
introduced a new state: Init. The router is in this state only when it's
created.

We have cleaned up router status management which is now handled by
manageStatus function only.
2019-07-01 15:46:26 +01:00
Milos Gajdos
32300eadc1 Added Router Status which allows to track router status 2019-07-01 15:46:25 +01:00
Milos Gajdos
8ad2f73ad6 Advertisement is now Update; started bit is now running. 2019-07-01 15:46:25 +01:00
Milos Gajdos
9d7420658d Changed router interface. Added table watcher. Advertise routes
* Changed router interface to return Advertisement channel
* Added default gateway route to the routing table if supplied
* Watch table for updates and advertise to the network
* We hash the routes on 3-tuple (Destination, Gateway, Network)
2019-07-01 15:46:25 +01:00
Asim Aslam
0971deb9cc Merge pull request #558 from micro/network
Networking code
2019-07-01 12:12:23 +01:00
Asim Aslam
0899282277 Checkpoint networking code 2019-07-01 11:55:15 +01:00
Asim Aslam
d8e998ad85 add peer in context 2019-06-27 14:53:01 +01:00
Asim Aslam
b4b76d452a Call advertise 2019-06-27 14:38:12 +01:00
Asim Aslam
67e3d560fe Lookup every service. FML 2019-06-27 14:37:52 +01:00
Asim Aslam
9630e153a5 fix grpc proto wrapper 2019-06-27 13:08:06 +01:00
Asim Aslam
43297f731c Add default router 2019-06-27 12:57:23 +01:00
Asim Aslam
f6f6e1b561 Use the router to get routes 2019-06-27 12:56:52 +01:00
Asim Aslam
4bee5c1b2b Merge pull request #546 from lpxxn/master
pass parameter to anonymous function
2019-06-27 07:02:45 +01:00
lpxxn
3b0ef425b6 pass parameter to anonymous function 2019-06-27 13:06:53 +08:00
李鹏
5334203435 Merge pull request #4 from micro/master
pull
2019-06-27 13:01:14 +08:00
Asim Aslam
0da8256426 Accept a range of addresses 2019-06-26 20:51:13 +01:00
Asim Aslam
940ea94a96 Lookup router via registry 2019-06-26 19:56:40 +01:00
Asim Aslam
b904f383c1 go fmt 2019-06-26 19:28:30 +01:00
Asim Aslam
cedcef032d Add remote lookup via router selector 2019-06-26 19:27:38 +01:00
Milos Gajdos
76011b151d Bugfix: Set gateway to node.Address
gw has not been initialized; it was basically an empty string and only
got populated by Sprintf-ing the addr:port IF the port has been set.
This commit sets the gw to node.Address to it's never an empty string.
2019-06-26 16:28:33 +01:00
Asim Aslam
27b145f968 add router proto 2019-06-26 16:23:10 +01:00
Asim Aslam
ac098e4d78 add router selector and network defaults 2019-06-26 16:12:57 +01:00
Asim Aslam
1a62c11166 Merge pull request #544 from milosgajdos83/router-rework
Router rework
2019-06-26 16:08:12 +01:00
Milos Gajdos
fe84a2d726 Route per service node. No Network Registry for now. 2019-06-26 16:03:19 +01:00
李鹏
c282125f09 Merge pull request #3 from micro/master
update
2019-06-26 11:56:00 +08:00
Asim Aslam
4cad7697cc Merge pull request #542 from magodo/config_consul_source_opt
Add consul-specific option for config (as registry)
2019-06-25 16:14:03 +01:00
magodo
a8dbca756c rename stuff per feedback 2019-06-25 22:41:31 +08:00
magodo
8e4fd16aff Add consul-specific option for config (as registry) 2019-06-25 18:31:32 +08:00
Asim Aslam
68764ebafc Add registry resolver 2019-06-24 15:30:17 +01:00
Asim Aslam
4d08618517 fix typo 2019-06-24 15:22:12 +01:00
Asim Aslam
e5959f80d6 add http resolver 2019-06-24 15:21:24 +01:00
Asim Aslam
b89423bf37 add resolver 2019-06-24 15:11:11 +01:00
Asim Aslam
9a56c4e0b2 Merge branch 'master' of ssh://github.com/micro/go-micro 2019-06-24 14:49:26 +01:00
Asim Aslam
4f982bb9cd Default to json content-type in api 2019-06-24 14:49:19 +01:00
Asim Aslam
1277f2478d Merge pull request #541 from milosgajdos83/gossip-del-service-revert
Reverts c0a628d
2019-06-22 20:05:10 +01:00
Asim Aslam
dffbe045e4 move node functions 2019-06-22 19:02:57 +01:00
Milos Gajdos
c3d2043caf Reverts c0a628d65b
Fixes #540
2019-06-22 19:01:03 +01:00
Asim Aslam
79cc8e34b0 Merge branch 'master' of ssh://github.com/micro/go-micro 2019-06-22 16:51:28 +01:00
Asim Aslam
2d91ba411e update the network interface 2019-06-22 16:51:20 +01:00
Asim Aslam
5ee7140aa3 Merge pull request #536 from magodo/config_source_consul_support_array
Config source consul support 1st array
2019-06-22 08:39:17 +01:00
magodo
6ef838c9aa Merge branch 'master' of https://github.com/micro/go-micro into config_source_consul_support_array 2019-06-22 07:14:15 +08:00
Asim Aslam
1b4005e9a5 Go fmt everything 2019-06-21 17:20:41 +01:00
Asim Aslam
3f97743e34 Move router and proxy into network package 2019-06-21 17:20:31 +01:00
Asim Aslam
7936d74602 Update comments 2019-06-21 16:17:12 +01:00
Asim Aslam
6db720b197 Merge branch 'master' of ssh://github.com/micro/go-micro 2019-06-21 15:14:08 +01:00
Asim Aslam
ca5acba0c6 Move selector to client/selector 2019-06-21 15:13:54 +01:00
Asim Aslam
b4acb9bb58 Merge pull request #538 from magodo/consul_path_prefix_leading_slash
config consul source supports slash as prefix
2019-06-21 14:23:53 +01:00
Asim Aslam
c350e19552 Move cmd => config/cmd 2019-06-21 13:36:11 +01:00
Asim Aslam
4aa0192eba Update go mod 2019-06-21 12:55:31 +01:00
magodo
3c82b2e9e8 Merge branch 'consul_path_prefix_leading_slash' into dev 2019-06-21 16:53:21 +08:00
magodo
9514bd7b2a Merge branch 'config_source_consul_support_array' into dev 2019-06-21 16:52:01 +08:00
magodo
7acd249147 config consul source supports slash as prefix
`config.NewConfig()` with consul source will both read from consul
and watch consul for changes. Hence, the `prefix` is used in these
2 cases:

- read case: it is used to strip path based on the `KVPair` returned
from consul `kv.List()` method
- watch case: it is used as the `key` of watch query (`keyprefix` type)

So for *watch case*, the `key` is leagal to be `/` for watching change
on root. While for *read case*, because `KVPair.Key` is always stripped
off the leading slash, so if user specified some `prefix` with leading
slash, we should strip it also.

An extream case would be: user want's to read & watch node in root dir.
One would specify `prefix` as `/`, and it should work then.
2019-06-21 16:35:48 +08:00
magodo
1983b4ae92 variable rename to abstract encoder 2019-06-21 15:30:45 +08:00
magodo
92b998c3ab consul config source support 1st-level array
Check whetehr the 1st level encoded json is array or not, to
support 1st level array in consul config.

During debug, i suspected the incapability of arrray is caused by
json reader, so i added test for array. I think it makes no harm
to also check that in.
2019-06-21 00:25:39 +08:00
Milos Gajdos
1765be049b router.Start() is now router.Advertise(). Updated code documentation. 2019-06-20 13:04:58 +01:00
Asim Aslam
8d5d812e32 Fix a streaming bug 2019-06-20 12:44:51 +01:00
Asim Aslam
3f910038a3 Move store to data/store 2019-06-19 22:04:13 +01:00
Asim Aslam
a8042adac1 Merge pull request #528 from milosgajdos83/router
Adds router package
2019-06-19 21:33:39 +01:00
Milos Gajdos
10a3636a9f Renamed variables, options and functions 2019-06-19 21:22:14 +01:00
Milos Gajdos
4e5fbbf7eb Replaced the debug network string by the correct router local address. 2019-06-19 18:11:16 +01:00
Milos Gajdos
59035ab801 Removed debug logs. advertiseToNetwork() replaced watchTable().
Debug logs that were helpful when squashing bugs have been removed.

advertiseToNetwork replaced the watchTable which originally watched the
routing table entries. We now take a different approach to propagating
the local registry services into the network registry.
2019-06-19 18:03:43 +01:00
Milos Gajdos
d3525ebab3 Debug messages. Squashed Add Route bugs and few others. 2019-06-19 18:03:43 +01:00
Milos Gajdos
2674294cbe Delete route when no node is available. 2019-06-19 18:03:43 +01:00
Milos Gajdos
b20dd16f92 Watcher now emits events instead of results. 2019-06-19 18:03:43 +01:00
Milos Gajdos
5088c9d916 Increased Network registry TTL. Routing Table remove is now delete.
Remove has been renamed to Delete to be more in line with the framework.

A bunch of comments have been added/updated for the future generations

We have increased the Network Registry TTL to 2 minutes.
2019-06-19 18:03:42 +01:00
Milos Gajdos
f62fcaad76 Added router ID. Deregister remote services when router is stopped.
Added ID function to router interface.

Network registry addresses are deregistered when the router is stopped.

Query has been updated to search for particular GW in lookups.
2019-06-19 18:03:42 +01:00
Milos Gajdos
322eaae529 Small code refactoring. Added more comments and parseToNode func 2019-06-19 18:03:42 +01:00
Milos Gajdos
6a33b7576b Removed router watcher code duplication. Small code refactor. 2019-06-19 18:03:42 +01:00
Milos Gajdos
6e669d4611 Reorganised source. Renamed files. No Code change. 2019-06-19 18:03:42 +01:00
Milos Gajdos
95fc625e99 Big refactor. New Registry watchers. New options. New names. 2019-06-19 18:03:42 +01:00
Milos Gajdos
338e0fdf18 Lots of refactoring. We now have basic routing table watcher. 2019-06-19 18:03:42 +01:00
Milos Gajdos
5899134b66 Simplified API. Correct Router initialization. Debug printing. 2019-06-19 18:03:41 +01:00
Milos Gajdos
da18ea4ab5 Changed default router table modifications. Entry is now Route. 2019-06-19 18:03:41 +01:00
Milos Gajdos
459f4c8387 Added Router ID and query options to limit number of results 2019-06-19 18:03:41 +01:00
Milos Gajdos
9c57f32f58 Added Entry type. Basic implementation of Router and Table 2019-06-19 18:03:41 +01:00
Milos Gajdos
ad92e6821e Removed DefaultTable() from global vars
We will not initialize DefaultTable as global var unless the users asks
for it explicitly.
2019-06-19 18:03:41 +01:00
Milos Gajdos
d7f0db04ec Added network ID option. Added mutex to routing table. 2019-06-19 18:03:41 +01:00
Milos Gajdos
e4311c3a10 Redefined and polished some interfaces and data structures. 2019-06-19 18:03:41 +01:00
Milos Gajdos
ee8b6b3114 Redefeind interfaces; Added better modelled data strauctures
Router interface has been redefined which fits better with what we are
looking for.

Routing table now offers a comprehensive set of information about its
entries which will make up for rich queries in the future

Query interface has been defined to enable current basic and more
advanced queries in the future.
2019-06-19 18:03:41 +01:00
Milos Gajdos
08da7c1283 First commit: Outline of Router interface 2019-06-19 18:03:40 +01:00
Asim Aslam
6587ae07be Merge pull request #523 from micro/grpc
GRPC Proxy
2019-06-19 15:31:45 +01:00
Asim Aslam
1c1dae0642 Fix the grpc test 2019-06-19 12:34:45 +01:00
Asim Aslam
a0cb105cf6 Merge pull request #525 from magodo/consul_config_prefix_no_leading_slash
`prefix` in consul api starts with no leading slash
2019-06-19 08:12:35 +01:00
magodo
606b1ff7cf prefix in consul api starts with no leading slash
When `consul.StripPrefix(true)` is set, current impl. will pass the
specified prefix (or default prefix) when calling consul api.

However, `prefix` in consul api starts with no leading slash, so
the default prefix (`/micro/config`) doesn't actually work.

I avoid code changes (esp. the one in `util.go`) to eliminate
impact on users who already notice it.
2019-06-19 14:42:09 +08:00
Asim Aslam
73a8b14145 Merge pull request #524 from milosgajdos83/gosssip-remove-node
Properly delete service nodes
2019-06-19 07:11:27 +01:00
Milos Gajdos
c0a628d65b Simplified delService code; properly delete service nodes 2019-06-18 21:39:00 +01:00
Asim Aslam
e9c2df775a Merge branch 'master' into grpc 2019-06-18 18:51:55 +01:00
Asim Aslam
d3a6297b17 Add working grpc proxy config 2019-06-18 18:51:52 +01:00
Asim Aslam
7266c62d09 remove comment 2019-06-18 15:33:31 +01:00
Asim Aslam
6459cdfc21 propagate updates to local watchers 2019-06-18 14:42:56 +01:00
Asim Aslam
ed54384bf4 Update network 2019-06-18 11:56:11 +01:00
Asim Aslam
51560009d2 go fmt 2019-06-18 11:04:36 +01:00
Asim Aslam
cf2f8a9a55 Merge branch 'master' of ssh://github.com/micro/go-micro 2019-06-18 11:04:16 +01:00
Asim Aslam
97cf2cd7c3 go fmt 2019-06-18 11:04:06 +01:00
Asim Aslam
d9fe8f802b Merge pull request #522 from xpunch/grpcMessageIssue
grpc message should be able to set
2019-06-18 10:45:11 +01:00
johnson
b754c33549 grpc message should be able to set 2019-06-18 17:07:31 +08:00
Asim Aslam
59eaa89bac Node is a network 2019-06-17 21:11:39 +01:00
Asim Aslam
f65694670e add cruft 2019-06-17 20:05:58 +01:00
Asim Aslam
1a571b8c82 Add network transport 2019-06-17 18:25:42 +01:00
Asim Aslam
308673b393 add network package 2019-06-17 16:57:53 +01:00
Asim Aslam
3a454d870a Merge pull request #520 from xpunch/grpcSubscriberIssues
grpc server subscriber missing some bug fixings
2019-06-17 11:57:37 +01:00
johnson
baaa386e27 a. add default context type when header not found
b. return subscribe error after handler finished
2019-06-17 17:54:37 +08:00
Asim Aslam
a619321b64 Merge pull request #519 from xpunch/master
missing nil check for grpc WaitGroup
2019-06-17 10:30:28 +01:00
johnson
363fb551af missing nil check for grpc WaitGroup 2019-06-17 17:07:55 +08:00
Asim Aslam
7a87ae0efa Merge pull request #514 from unistack-org/cleanup
remove mock data from memory registry
2019-06-13 07:50:08 +01:00
ab692ff590 remove mock data from memory registry
memory registry can be used as fast inprocess registry,
so mock data needs to be in tests only

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2019-06-13 00:51:56 +03:00
Asim Aslam
2b18b11ab1 Merge pull request #513 from micro/crufting
Crufting
2019-06-12 13:03:17 +01:00
Asim Aslam
af096951fc update import names for mucp 2019-06-12 12:54:45 +01:00
Asim Aslam
97967cbe14 move options under config 2019-06-12 12:45:42 +01:00
Asim Aslam
a6e09c9249 Merge branch 'master' into crufting 2019-06-12 12:29:57 +01:00
Asim Aslam
000e25a4b2 use the router 2019-06-12 12:05:34 +01:00
Asim Aslam
7a1cef46b0 fix broken links 2019-06-12 07:50:04 +01:00
Asim Aslam
a5412dd4a0 Move data to store 2019-06-12 07:46:20 +01:00
Asim Aslam
f81f66c98b Move DB to Map 2019-06-11 18:21:33 +01:00
Asim Aslam
43ed8f58f0 change wording 2019-06-11 18:15:18 +01:00
Asim Aslam
7727b359c8 Add memory data store 2019-06-11 17:49:34 +01:00
Asim Aslam
8e4e710e15 Move data to top level 2019-06-11 17:20:52 +01:00
Asim Aslam
4d4686d9be Merge branch 'master' into crufting 2019-06-11 15:38:12 +01:00
Asim Aslam
6d06ee8078 Update go.mod to strip etcd 2019-06-11 11:40:37 +01:00
Asim Aslam
aec1ca6635 remove etcd source 2019-06-11 09:53:06 +01:00
Asim Aslam
235a653f78 check in cruft 2019-06-11 09:52:35 +01:00
Asim Aslam
d030c78d1c Merge pull request #509 from outshow/master
fix etcd error
2019-06-11 09:52:21 +01:00
outshow
90a9df9b8c 1. use github.com/coreos instead of go.etcd.io in etcd related import path; 2. add dialtimeout to etcd client 2019-06-11 16:18:37 +08:00
Asim Aslam
070bd40b4c Merge branch 'master' into crufting 2019-06-10 12:44:27 +01:00
Asim Aslam
46de3ae9a9 Fix text codec 2019-06-10 12:42:43 +01:00
Asim Aslam
b6833e478d Merge pull request #506 from milosgajdos83/consul-close-watcher
Return registry.ErrWatcherStopped when consul watcher stops
2019-06-09 16:03:06 +01:00
Milos Gajdos
73b0a0ed0e Return registry.ErrWatcherStopped when consul watcher stops.
The original code returns "result chan closed" errors.Error which does
not carry higher semantics signal to downstream despite go-micro having
a clearly defined Error for this behaviour. This commit fixes that and
lets the downstream i.e. consumer of this code to act based on different
errors.
2019-06-09 15:51:27 +01:00
Asim Aslam
7c4515d748 Merge pull request #504 from magodo/json_pb_support
unmarshal json with `jsonpb` if accepter is pb
2019-06-09 08:57:55 +01:00
magodo
748c20c979 use package level func for unmarshal 2019-06-09 11:55:36 +08:00
magodo
3573ac818f unmarshal json with jsonpb if accepter is pb 2019-06-09 11:50:50 +08:00
Asim Aslam
ed4bce3285 check in this cruft 2019-06-08 19:40:44 +01:00
Asim Aslam
95b8147fa1 Merge pull request #501 from micro/wrap
add the wrappers back into the core router
2019-06-07 15:22:16 +01:00
Asim Aslam
f5ac238231 Include the decoded body 2019-06-07 15:15:22 +01:00
Asim Aslam
bfdec9e2e3 add the wrappers back into the core router 2019-06-07 15:02:19 +01:00
Asim Aslam
a2fbf19341 Move sync deps, change uuid to google and update go.mod 2019-06-07 13:53:42 +01:00
Asim Aslam
9e23855c37 Fixup the proxy, strip down go.mod. Win bigly 2019-06-07 13:42:39 +01:00
Asim Aslam
d65393a799 add top level options comment 2019-06-07 11:18:08 +01:00
Asim Aslam
ef67dc7ceb Merge pull request #500 from leaxoy/clean-mod
cleanup go.mod remove replace section
2019-06-07 11:14:53 +01:00
Asim Aslam
c317daf6b8 update proxy/options 2019-06-06 21:45:28 +01:00
lixiaohui
1152c7cb03 cleanup go.mod remove replace section 2019-06-07 03:05:33 +08:00
Asim Aslam
2cc18d6edc fix errors 2019-06-06 17:58:21 +01:00
Asim Aslam
a58bc8e75c add proxy interface and move router packages 2019-06-06 17:55:32 +01:00
Asim Aslam
64459c54a1 move init to options 2019-06-06 17:54:30 +01:00
Asim Aslam
c60b5a45bb Add proxy interface 2019-06-06 17:49:41 +01:00
Asim Aslam
94772a8cc7 remove the proto from proxy package 2019-06-06 17:38:05 +01:00
Asim Aslam
52613190b0 remove micro.png 2019-06-06 17:08:04 +01:00
Milos Gajdos
a29ce20e31 Changed default NATS address to nats://127.0.0.1:4222 in nats test 2019-06-06 12:06:14 +01:00
Asim Aslam
d59b693fa6 update interface 2019-06-06 11:46:13 +01:00
Asim Aslam
deee4dcd6a Merge branch 'master' of ssh://github.com/micro/go-micro 2019-06-06 11:32:42 +01:00
Asim Aslam
ab7d036697 add init package 2019-06-06 11:32:38 +01:00
Milos Gajdos
de87dfb6a0 Added gitignore file to avoid committing unnecessary files 2019-06-06 10:56:20 +01:00
Asim Aslam
0f70281e28 remove swp file 2019-06-06 09:52:22 +01:00
Asim Aslam
9d5cde42a3 Add top level proxy comment 2019-06-06 09:50:25 +01:00
Asim Aslam
83f46d9c9d top level package comment for service 2019-06-06 09:02:00 +01:00
Asim Aslam
19de02646e Merge pull request #497 from unistack-org/logf
server fix log.Log -> log.Logf
2019-06-05 14:33:51 +01:00
695c546385 server fix log.Log -> log.Logf
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2019-06-05 15:09:26 +03:00
206 changed files with 8987 additions and 5884 deletions

32
.gitignore vendored Normal file
View File

@@ -0,0 +1,32 @@
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
# Folders
_obj
_test
_build
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
# Test binary, build with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# vim temp files
*~
*.swp
*.swo

View File

@@ -1,197 +0,0 @@
# Agent
Agent is a library used to create commands, inputs and robot services
## Getting Started
- [Commands](#commands) - Commands are functions executed by the bot based on text based pattern matching.
- [Inputs](#inputs) - Inputs are plugins for communication e.g Slack, Telegram, IRC, etc.
- [Services](#services) - Write bots as micro services
## Commands
Commands are functions executed by the bot based on text based pattern matching.
### Write a Command
```go
import "github.com/micro/go-micro/agent/command"
func Ping() command.Command {
usage := "ping"
description := "Returns pong"
return command.NewCommand("ping", usage, desc, func(args ...string) ([]byte, error) {
return []byte("pong"), nil
})
}
```
### Register the command
Add the command to the Commands map with a pattern key that can be matched by golang/regexp.Match
```go
import "github.com/micro/go-micro/agent/command"
func init() {
command.Commands["^ping$"] = Ping()
}
```
### Rebuild Micro
Build binary
```shell
cd github.com/micro/micro
// For local use
go build -i -o micro ./main.go
// For docker image
CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -ldflags '-w' -i -o micro ./main.go
```
## Inputs
Inputs are plugins for communication e.g Slack, HipChat, XMPP, IRC, SMTP, etc, etc.
New inputs can be added in the following way.
### Write an Input
Write an input that satisfies the Input interface.
```go
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
}
```
### Register the input
Add the input to the Inputs map.
```go
import "github.com/micro/micro/bot/input"
func init() {
input.Inputs["name"] = MyInput
}
```
### Rebuild Micro
Build binary
```shell
cd github.com/micro/micro
// For local use
go build -i -o micro ./main.go
// For docker image
CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -ldflags '-w' -i -o micro ./main.go
```
## Services
The micro bot supports the ability to create commands as micro services.
### How does it work?
The bot watches the service registry for services with it's namespace. The default namespace is `go.micro.bot`.
Any service within this namespace will automatically be added to the list of available commands. When a command
is executed, the bot will call the service with method `Command.Exec`. It also expects the method `Command.Help`
to exist for usage info.
The service interface is as follows and can be found at [go-micro/agent/proto](https://github.com/micro/go-micro/agent/blob/master/proto/bot.proto)
```
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;
}
```
### Example
Here's an example echo command as a microservice
```go
package main
import (
"fmt"
"strings"
"github.com/micro/go-micro"
"golang.org/x/net/context"
proto "github.com/micro/go-micro/agent/proto"
)
type Command struct{}
// Help returns the command usage
func (c *Command) Help(ctx context.Context, req *proto.HelpRequest, rsp *proto.HelpResponse) error {
// Usage should include the name of the command
rsp.Usage = "echo"
rsp.Description = "This is an example bot command as a micro service which echos the message"
return nil
}
// Exec executes the command
func (c *Command) Exec(ctx context.Context, req *proto.ExecRequest, rsp *proto.ExecResponse) error {
rsp.Result = []byte(strings.Join(req.Args, " "))
// rsp.Error could be set to return an error instead
// the function error would only be used for service level issues
return nil
}
func main() {
service := micro.NewService(
micro.Name("go.micro.bot.echo"),
)
service.Init()
proto.RegisterCommandHandler(service.Server(), new(Command))
if err := service.Run(); err != nil {
fmt.Println(err)
}
}
```

View File

@@ -1,18 +0,0 @@
# Go API [![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/api?status.svg)](https://godoc.org/github.com/micro/go-micro/api) [![Travis CI](https://api.travis-ci.org/micro/go-micro/api.svg?branch=master)](https://travis-ci.org/micro/go-micro/api) [![Go Report Card](https://goreportcard.com/badge/micro/go-micro/api)](https://goreportcard.com/report/github.com/micro/go-micro/api)
Go API is a pluggable API framework driven by service discovery to help build powerful public API gateways.
## Overview
The Go API library provides api gateway routing capabilities. A microservice architecture decouples application logic into
separate service. An api gateway provides a single entry point to consolidate these services into a unified api. The
Go API uses routes defined in service discovery metadata to generate routing rules and serve http requests.
<img src="https://micro.mu/docs/images/go-api.png?v=1" alt="Go API" />
Go API is the basis for the [micro api](https://micro.mu/docs/api.html).
## Getting Started
See the [docs](https://micro.mu/docs/go-api.html) to learn more

View File

@@ -6,11 +6,11 @@ import (
goapi "github.com/micro/go-micro/api"
"github.com/micro/go-micro/api/handler"
"github.com/micro/go-micro/client"
"github.com/micro/go-micro/errors"
"github.com/micro/go-micro/selector"
"github.com/micro/go-micro/util/ctx"
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 {

View File

@@ -8,9 +8,9 @@ import (
"net/http"
"strings"
"github.com/micro/go-micro/registry"
"github.com/micro/go-micro/selector"
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) {

View File

@@ -120,7 +120,7 @@ func (c *conn) writeLoop() {
opts = append(opts, broker.Queue(c.queue))
}
subscriber, err := c.b.Subscribe(c.topic, func(p broker.Publication) error {
subscriber, err := c.b.Subscribe(c.topic, func(p broker.Event) error {
b, err := json.Marshal(p.Message())
if err != nil {
return nil

View File

@@ -31,7 +31,7 @@ import (
"time"
"unicode"
"github.com/pborman/uuid"
"github.com/google/uuid"
"gopkg.in/go-playground/validator.v9"
)
@@ -66,7 +66,7 @@ func New(eventType string, mimeType string, payload interface{}) *Event {
EventType: eventType,
CloudEventsVersion: CloudEventsVersion,
Source: "https://micro.mu",
EventID: uuid.NewUUID().String(),
EventID: uuid.New().String(),
EventTime: &now,
ContentType: mimeType,
Data: payload,

View File

@@ -10,10 +10,10 @@ import (
"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"
"github.com/pborman/uuid"
)
type event struct {
@@ -73,7 +73,7 @@ func (e *event) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ev := &proto.Event{
Name: action,
// TODO: dedupe event
Id: fmt.Sprintf("%s-%s-%s", topic, action, uuid.NewUUID().String()),
Id: fmt.Sprintf("%s-%s-%s", topic, action, uuid.New().String()),
Header: make(map[string]*proto.Pair),
Timestamp: time.Now().Unix(),
}

View File

@@ -10,7 +10,7 @@ import (
"github.com/micro/go-micro/api"
"github.com/micro/go-micro/api/handler"
"github.com/micro/go-micro/selector"
"github.com/micro/go-micro/client/selector"
)
const (
@@ -73,7 +73,7 @@ func (h *httpHandler) getService(r *http.Request) (string, error) {
return "", nil
}
return fmt.Sprintf("http://%s:%d", s.Address, s.Port), nil
return fmt.Sprintf("http://%s", s.Address), nil
}
func (h *httpHandler) String() string {

View File

@@ -4,14 +4,12 @@ import (
"net"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"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/cmd"
"github.com/micro/go-micro/config/cmd"
"github.com/micro/go-micro/registry"
"github.com/micro/go-micro/registry/memory"
)
@@ -26,21 +24,12 @@ func testHttp(t *testing.T, path, service, ns string) {
}
defer l.Close()
parts := strings.Split(l.Addr().String(), ":")
var host string
var port int
host = parts[0]
port, _ = strconv.Atoi(parts[1])
s := &registry.Service{
Name: service,
Nodes: []*registry.Node{
&registry.Node{
Id: service + "-1",
Address: host,
Port: port,
Address: l.Addr().String(),
},
},
}

View File

@@ -14,12 +14,12 @@ import (
"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/selector"
"github.com/micro/go-micro/util/ctx"
)
@@ -120,32 +120,6 @@ func (h *rpcHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var rsp []byte
switch {
// json codecs
case hasCodec(ct, jsonCodecs):
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()
// proto codecs
case hasCodec(ct, protoCodecs):
request := &proto.Message{}
@@ -173,8 +147,36 @@ func (h *rpcHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// marshall response
rsp, _ = response.Marshal()
default:
http.Error(w, "Unsupported Content-Type", 400)
return
// 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

View File

@@ -13,7 +13,7 @@ import (
"github.com/micro/go-micro/api"
"github.com/micro/go-micro/api/handler"
"github.com/micro/go-micro/selector"
"github.com/micro/go-micro/client/selector"
)
const (
@@ -79,7 +79,7 @@ func (wh *webHandler) getService(r *http.Request) (string, error) {
return "", nil
}
return fmt.Sprintf("http://%s:%d", s.Address, s.Port), nil
return fmt.Sprintf("http://%s", s.Address), nil
}
// serveWebSocket used to serve a web socket proxied connection

View File

@@ -3,7 +3,7 @@ package router
import (
"github.com/micro/go-micro/api/resolver"
"github.com/micro/go-micro/api/resolver/micro"
"github.com/micro/go-micro/cmd"
"github.com/micro/go-micro/config/cmd"
"github.com/micro/go-micro/registry"
)

View File

@@ -3,28 +3,28 @@ package broker
// Broker is an interface used for asynchronous messaging.
type Broker interface {
Init(...Option) error
Options() Options
Address() string
Connect() error
Disconnect() error
Init(...Option) error
Publish(string, *Message, ...PublishOption) error
Subscribe(string, Handler, ...SubscribeOption) (Subscriber, error)
Publish(topic string, m *Message, opts ...PublishOption) error
Subscribe(topic string, h Handler, opts ...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(Publication) error
type Handler func(Event) error
type Message struct {
Header map[string]string
Body []byte
}
// Publication is given to a subscription handler for processing
type Publication interface {
// Event is given to a subscription handler for processing
type Event interface {
Topic() string
Message() *Message
Ack() error

View File

@@ -1,4 +1,4 @@
package memory
package broker
import (
"github.com/micro/go-micro/registry"
@@ -6,7 +6,7 @@ import (
var (
// mock data
Data = map[string][]*registry.Service{
testData = map[string][]*registry.Service{
"foo": []*registry.Service{
{
Name: "foo",
@@ -14,13 +14,11 @@ var (
Nodes: []*registry.Node{
{
Id: "foo-1.0.0-123",
Address: "localhost",
Port: 9999,
Address: "localhost:9999",
},
{
Id: "foo-1.0.0-321",
Address: "localhost",
Port: 9999,
Address: "localhost:9999",
},
},
},
@@ -30,8 +28,7 @@ var (
Nodes: []*registry.Node{
{
Id: "foo-1.0.1-321",
Address: "localhost",
Port: 6666,
Address: "localhost:6666",
},
},
},
@@ -41,8 +38,7 @@ var (
Nodes: []*registry.Node{
{
Id: "foo-1.0.3-345",
Address: "localhost",
Port: 8888,
Address: "localhost:8888",
},
},
},

View File

@@ -13,8 +13,6 @@ import (
"net/http"
"net/url"
"runtime"
"strconv"
"strings"
"sync"
"time"
@@ -59,7 +57,7 @@ type httpSubscriber struct {
hb *httpBroker
}
type httpPublication struct {
type httpEvent struct {
m *Message
t string
}
@@ -155,15 +153,15 @@ func newHttpBroker(opts ...Option) Broker {
return h
}
func (h *httpPublication) Ack() error {
func (h *httpEvent) Ack() error {
return nil
}
func (h *httpPublication) Message() *Message {
func (h *httpEvent) Message() *Message {
return h.m
}
func (h *httpPublication) Topic() string {
func (h *httpEvent) Topic() string {
return h.t
}
@@ -323,7 +321,7 @@ func (h *httpBroker) ServeHTTP(w http.ResponseWriter, req *http.Request) {
return
}
p := &httpPublication{m: m, t: topic}
p := &httpEvent{m: m, t: topic}
id := req.Form.Get("id")
h.RLock()
@@ -403,6 +401,7 @@ func (h *httpBroker) Connect() error {
go func() {
h.run(l)
h.Lock()
h.opts.Addrs = []string{addr}
h.address = addr
h.Unlock()
}()
@@ -542,7 +541,7 @@ func (h *httpBroker) Publish(topic string, msg *Message, opts ...PublishOption)
vals := url.Values{}
vals.Add("id", node.Id)
uri := fmt.Sprintf("%s://%s:%d%s?%s", scheme, node.Address, node.Port, DefaultSubPath, vals.Encode())
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
@@ -613,12 +612,15 @@ func (h *httpBroker) Publish(topic string, msg *Message, opts ...PublishOption)
}
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
parts := strings.Split(h.Address(), ":")
host := strings.Join(parts[:len(parts)-1], ":")
port, _ := strconv.Atoi(parts[len(parts)-1])
host, port, err = net.SplitHostPort(h.Address())
if err != nil {
return nil, err
}
addr, err := maddr.Extract(host)
if err != nil {
@@ -637,8 +639,7 @@ func (h *httpBroker) Subscribe(topic string, handler Handler, opts ...SubscribeO
// register service
node := &registry.Node{
Id: id,
Address: addr,
Port: port,
Address: mnet.HostPort(addr, port),
Metadata: map[string]string{
"secure": fmt.Sprintf("%t", secure),
},

View File

@@ -14,7 +14,7 @@ import (
func newTestRegistry() *memory.Registry {
r := memory.NewRegistry()
m := r.(*memory.Registry)
m.Setup()
m.Services = testData
return m
}
@@ -47,7 +47,7 @@ func sub(be *testing.B, c int) {
done := make(chan bool, c)
for i := 0; i < c; i++ {
sub, err := b.Subscribe(topic, func(p Publication) error {
sub, err := b.Subscribe(topic, func(p Event) error {
done <- true
m := p.Message()
@@ -107,7 +107,7 @@ func pub(be *testing.B, c int) {
done := make(chan bool, c*4)
sub, err := b.Subscribe(topic, func(p Publication) error {
sub, err := b.Subscribe(topic, func(p Event) error {
done <- true
m := p.Message()
if string(m.Body) != string(msg.Body) {
@@ -175,7 +175,7 @@ func TestBroker(t *testing.T) {
done := make(chan bool)
sub, err := b.Subscribe("test", func(p Publication) error {
sub, err := b.Subscribe("test", func(p Event) error {
m := p.Message()
if string(m.Body) != string(msg.Body) {
@@ -224,7 +224,7 @@ func TestConcurrentSubBroker(t *testing.T) {
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
sub, err := b.Subscribe("test", func(p Publication) error {
sub, err := b.Subscribe("test", func(p Event) error {
defer wg.Done()
m := p.Message()
@@ -279,7 +279,7 @@ func TestConcurrentPubBroker(t *testing.T) {
var wg sync.WaitGroup
sub, err := b.Subscribe("test", func(p Publication) error {
sub, err := b.Subscribe("test", func(p Event) error {
defer wg.Done()
m := p.Message()

View File

@@ -3,21 +3,26 @@ 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 memoryPublication struct {
type memoryEvent struct {
topic string
message *broker.Message
}
@@ -35,7 +40,7 @@ func (m *memoryBroker) Options() broker.Options {
}
func (m *memoryBroker) Address() string {
return ""
return m.addr
}
func (m *memoryBroker) Connect() error {
@@ -46,6 +51,15 @@ func (m *memoryBroker) Connect() error {
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
@@ -72,19 +86,19 @@ func (m *memoryBroker) Init(opts ...broker.Option) error {
}
func (m *memoryBroker) Publish(topic string, message *broker.Message, opts ...broker.PublishOption) error {
m.Lock()
defer m.Unlock()
m.RLock()
if !m.connected {
m.RUnlock()
return errors.New("not connected")
}
subs, ok := m.Subscribers[topic]
m.RUnlock()
if !ok {
return nil
}
p := &memoryPublication{
p := &memoryEvent{
topic: topic,
message: message,
}
@@ -99,12 +113,12 @@ func (m *memoryBroker) Publish(topic string, message *broker.Message, opts ...br
}
func (m *memoryBroker) Subscribe(topic string, handler broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) {
m.Lock()
defer m.Unlock()
m.RLock()
if !m.connected {
m.RUnlock()
return nil, errors.New("not connected")
}
m.RUnlock()
var options broker.SubscribeOptions
for _, o := range opts {
@@ -119,7 +133,9 @@ func (m *memoryBroker) Subscribe(topic string, handler broker.Handler, opts ...b
opts: options,
}
m.Lock()
m.Subscribers[topic] = append(m.Subscribers[topic], sub)
m.Unlock()
go func() {
<-sub.exit
@@ -142,15 +158,15 @@ func (m *memoryBroker) String() string {
return "memory"
}
func (m *memoryPublication) Topic() string {
func (m *memoryEvent) Topic() string {
return m.topic
}
func (m *memoryPublication) Message() *broker.Message {
func (m *memoryEvent) Message() *broker.Message {
return m.message
}
func (m *memoryPublication) Ack() error {
func (m *memoryEvent) Ack() error {
return nil
}
@@ -169,6 +185,7 @@ func (m *memorySubscriber) Unsubscribe() error {
func NewBroker(opts ...broker.Option) broker.Broker {
var options broker.Options
rand.Seed(time.Now().UnixNano())
for _, o := range opts {
o(&options)
}

View File

@@ -17,7 +17,7 @@ func TestMemoryBroker(t *testing.T) {
topic := "test"
count := 10
fn := func(p broker.Publication) error {
fn := func(p broker.Event) error {
return nil
}

View File

@@ -38,7 +38,7 @@ var addrTestCases = []struct {
"default",
"check if default Address is set correctly",
map[string]string{
"nats://localhost:4222": "",
"nats://127.0.0.1:4222": "",
},
},
}

View File

@@ -1,14 +0,0 @@
package client
import (
"bytes"
)
type buffer struct {
*bytes.Buffer
}
func (b *buffer) Close() error {
b.Buffer.Reset()
return nil
}

View File

@@ -10,7 +10,7 @@ import (
// Client is the interface used to make requests to services.
// It supports Request/Response via Transport and Publishing via the Broker.
// It also supports bidiectional streaming of requests.
// It also supports bidirectional streaming of requests.
type Client interface {
Init(...Option) error
Options() Options

47
client/common_test.go Normal file
View File

@@ -0,0 +1,47 @@
package client
import (
"github.com/micro/go-micro/registry"
)
var (
// mock data
testData = map[string][]*registry.Service{
"foo": []*registry.Service{
{
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",
},
},
},
},
}
)

View File

@@ -1,14 +0,0 @@
package grpc
import (
"bytes"
)
type buffer struct {
*bytes.Buffer
}
func (b *buffer) Close() error {
b.Buffer.Reset()
return nil
}

View File

@@ -2,12 +2,18 @@ package grpc
import (
"fmt"
"strings"
b "bytes"
"github.com/golang/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
"github.com/json-iterator/go"
jsoniter "github.com/json-iterator/go"
"github.com/micro/go-micro/codec"
"github.com/micro/go-micro/codec/bytes"
"github.com/micro/go-micro/codec/jsonrpc"
"github.com/micro/go-micro/codec/protorpc"
"google.golang.org/grpc"
"google.golang.org/grpc/encoding"
)
@@ -16,6 +22,8 @@ type protoCodec struct{}
type bytesCodec struct{}
type wrapCodec struct{ encoding.Codec }
var jsonpbMarshaler = &jsonpb.Marshaler{}
var (
defaultGRPCCodecs = map[string]encoding.Codec{
"application/json": jsonCodec{},
@@ -52,7 +60,28 @@ func (w wrapCodec) String() string {
return w.Codec.Name()
}
func (w wrapCodec) Marshal(v interface{}) ([]byte, error) {
b, ok := v.(*bytes.Frame)
if ok {
return b.Data, nil
}
return w.Codec.Marshal(v)
}
func (w wrapCodec) Unmarshal(data []byte, v interface{}) error {
b, ok := v.(*bytes.Frame)
if ok {
b.Data = data
return nil
}
return w.Codec.Unmarshal(data, v)
}
func (protoCodec) Marshal(v interface{}) ([]byte, error) {
b, ok := v.(*bytes.Frame)
if ok {
return b.Data, nil
}
return proto.Marshal(v.(proto.Message))
}
@@ -86,13 +115,79 @@ func (bytesCodec) Name() string {
}
func (jsonCodec) Marshal(v interface{}) ([]byte, error) {
if pb, ok := v.(proto.Message); ok {
s, err := jsonpbMarshaler.MarshalToString(pb)
return []byte(s), err
}
return json.Marshal(v)
}
func (jsonCodec) Unmarshal(data []byte, v interface{}) error {
if pb, ok := v.(proto.Message); ok {
return jsonpb.Unmarshal(b.NewReader(data), pb)
}
return json.Unmarshal(data, v)
}
func (jsonCodec) Name() string {
return "json"
}
type grpcCodec struct {
// headers
id string
target string
method string
endpoint string
s grpc.ClientStream
c encoding.Codec
}
func (g *grpcCodec) ReadHeader(m *codec.Message, mt codec.MessageType) error {
md, err := g.s.Header()
if err != nil {
return err
}
if m == nil {
m = new(codec.Message)
}
if m.Header == nil {
m.Header = make(map[string]string)
}
for k, v := range md {
m.Header[k] = strings.Join(v, ",")
}
m.Id = g.id
m.Target = g.target
m.Method = g.method
m.Endpoint = g.endpoint
return nil
}
func (g *grpcCodec) ReadBody(v interface{}) error {
if f, ok := v.(*bytes.Frame); ok {
return g.s.RecvMsg(f)
}
return g.s.RecvMsg(v)
}
func (g *grpcCodec) Write(m *codec.Message, v interface{}) error {
// if we don't have a body
if v != nil {
return g.s.SendMsg(v)
}
// write the body using the framing codec
return g.s.SendMsg(&bytes.Frame{m.Body})
}
func (g *grpcCodec) Close() error {
return g.s.CloseSend()
}
func (g *grpcCodec) String() string {
return g.c.Name()
}

View File

@@ -2,22 +2,23 @@
package grpc
import (
"bytes"
"context"
"crypto/tls"
"fmt"
"os"
"sync"
"time"
"github.com/micro/go-micro/broker"
"github.com/micro/go-micro/client"
"github.com/micro/go-micro/client/selector"
"github.com/micro/go-micro/codec"
"github.com/micro/go-micro/errors"
"github.com/micro/go-micro/metadata"
"github.com/micro/go-micro/registry"
"github.com/micro/go-micro/selector"
"github.com/micro/go-micro/transport"
"github.com/micro/go-micro/util/buf"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/encoding"
@@ -31,8 +32,9 @@ type grpcClient struct {
}
func init() {
encoding.RegisterCodec(jsonCodec{})
encoding.RegisterCodec(bytesCodec{})
encoding.RegisterCodec(wrapCodec{jsonCodec{}})
encoding.RegisterCodec(wrapCodec{protoCodec{}})
encoding.RegisterCodec(wrapCodec{bytesCodec{}})
}
// secure returns the dial option for whether its a secure or insecure connection
@@ -48,17 +50,29 @@ func (g *grpcClient) secure() grpc.DialOption {
}
func (g *grpcClient) next(request client.Request, opts client.CallOptions) (selector.Next, error) {
service := request.Service()
// get proxy
if prx := os.Getenv("MICRO_PROXY"); len(prx) > 0 {
service = prx
}
// get proxy address
if prx := os.Getenv("MICRO_PROXY_ADDRESS"); len(prx) > 0 {
opts.Address = []string{prx}
}
// return remote address
if len(opts.Address) > 0 {
return func() (*registry.Node, error) {
return &registry.Node{
Address: opts.Address,
Address: opts.Address[0],
}, nil
}, nil
}
// get next nodes from the selector
next, err := g.opts.Selector.Select(request.Service(), opts.SelectOptions...)
next, err := g.opts.Selector.Select(service, opts.SelectOptions...)
if err != nil && err == selector.ErrNotFound {
return nil, errors.NotFound("go.micro.client", err.Error())
} else if err != nil {
@@ -70,9 +84,6 @@ func (g *grpcClient) next(request client.Request, opts client.CallOptions) (sele
func (g *grpcClient) call(ctx context.Context, node *registry.Node, req client.Request, rsp interface{}, opts client.CallOptions) error {
address := node.Address
if node.Port > 0 {
address = fmt.Sprintf("%s:%d", address, node.Port)
}
header := make(map[string]string)
if md, ok := metadata.FromContext(ctx); ok {
@@ -99,7 +110,7 @@ func (g *grpcClient) call(ctx context.Context, node *registry.Node, req client.R
var grr error
cc, err := g.pool.getConn(address, grpc.WithDefaultCallOptions(grpc.CallCustomCodec(cf)),
cc, err := g.pool.getConn(address, grpc.WithDefaultCallOptions(grpc.ForceCodec(cf)),
grpc.WithTimeout(opts.DialTimeout), g.secure(),
grpc.WithDefaultCallOptions(
grpc.MaxCallRecvMsgSize(maxRecvMsgSize),
@@ -116,7 +127,7 @@ func (g *grpcClient) call(ctx context.Context, node *registry.Node, req client.R
ch := make(chan error, 1)
go func() {
err := cc.Invoke(ctx, methodToGRPC(req.Endpoint(), req.Body()), req.Body(), rsp, grpc.CallContentSubtype(cf.String()))
err := cc.Invoke(ctx, methodToGRPC(req.Service(), req.Endpoint()), req.Body(), rsp, grpc.CallContentSubtype(cf.Name()))
ch <- microError(err)
}()
@@ -132,9 +143,6 @@ func (g *grpcClient) call(ctx context.Context, node *registry.Node, req client.R
func (g *grpcClient) stream(ctx context.Context, node *registry.Node, req client.Request, opts client.CallOptions) (client.Stream, error) {
address := node.Address
if node.Port > 0 {
address = fmt.Sprintf("%s:%d", address, node.Port)
}
header := make(map[string]string)
if md, ok := metadata.FromContext(ctx); ok {
@@ -164,7 +172,10 @@ func (g *grpcClient) stream(ctx context.Context, node *registry.Node, req client
dialCtx, cancel = context.WithCancel(ctx)
}
defer cancel()
cc, err := grpc.DialContext(dialCtx, address, grpc.WithDefaultCallOptions(grpc.CallCustomCodec(cf)), g.secure())
wc := wrapCodec{cf}
cc, err := grpc.DialContext(dialCtx, address, grpc.WithDefaultCallOptions(grpc.ForceCodec(wc)), g.secure())
if err != nil {
return nil, errors.InternalServerError("go.micro.client", fmt.Sprintf("Error sending request: %v", err))
}
@@ -175,16 +186,34 @@ func (g *grpcClient) stream(ctx context.Context, node *registry.Node, req client
ServerStreams: true,
}
st, err := cc.NewStream(ctx, desc, methodToGRPC(req.Endpoint(), req.Body()), grpc.CallContentSubtype(cf.String()))
st, err := cc.NewStream(ctx, desc, methodToGRPC(req.Service(), req.Endpoint()))
if err != nil {
return nil, errors.InternalServerError("go.micro.client", fmt.Sprintf("Error creating stream: %v", err))
}
codec := &grpcCodec{
s: st,
c: wc,
}
// set request codec
if r, ok := req.(*grpcRequest); ok {
r.codec = codec
}
rsp := &response{
conn: cc,
stream: st,
codec: cf,
gcodec: codec,
}
return &grpcStream{
context: ctx,
request: req,
stream: st,
conn: cc,
context: ctx,
request: req,
response: rsp,
stream: st,
conn: cc,
}, nil
}
@@ -210,7 +239,7 @@ func (g *grpcClient) maxSendMsgSizeValue() int {
return v.(int)
}
func (g *grpcClient) newGRPCCodec(contentType string) (grpc.Codec, error) {
func (g *grpcClient) newGRPCCodec(contentType string) (encoding.Codec, error) {
codecs := make(map[string]encoding.Codec)
if g.opts.Context != nil {
if v := g.opts.Context.Value(codecsKey{}); v != nil {
@@ -260,7 +289,7 @@ func (g *grpcClient) Options() client.Options {
}
func (g *grpcClient) NewMessage(topic string, msg interface{}, opts ...client.MessageOption) client.Message {
return newGRPCPublication(topic, msg, "application/octet-stream")
return newGRPCEvent(topic, msg, g.opts.ContentType, opts...)
}
func (g *grpcClient) NewRequest(service, method string, req interface{}, reqOpts ...client.RequestOption) client.Request {
@@ -337,9 +366,9 @@ func (g *grpcClient) Call(ctx context.Context, req client.Request, rsp interface
var gerr error
for i := 0; i <= callOpts.Retries; i++ {
go func() {
go func(i int) {
ch <- call(i)
}()
}(i)
select {
case <-ctx.Done():
@@ -420,10 +449,10 @@ func (g *grpcClient) Stream(ctx context.Context, req client.Request, opts ...cli
var grr error
for i := 0; i <= callOpts.Retries; i++ {
go func() {
go func(i int) {
s, err := call(i)
ch <- response{s, err}
}()
}(i)
select {
case <-ctx.Done():
@@ -462,8 +491,9 @@ func (g *grpcClient) Publish(ctx context.Context, p client.Message, opts ...clie
return errors.InternalServerError("go.micro.client", err.Error())
}
b := &buffer{bytes.NewBuffer(nil)}
if err := cf(b).Write(&codec.Message{Type: codec.Publication}, p.Payload()); err != nil {
b := buf.New(nil)
if err := cf(b).Write(&codec.Message{Type: codec.Event}, p.Payload()); err != nil {
return errors.InternalServerError("go.micro.client", err.Error())
}

View File

@@ -3,14 +3,12 @@ package grpc
import (
"context"
"net"
"strconv"
"strings"
"testing"
"github.com/micro/go-micro/client"
"github.com/micro/go-micro/client/selector"
"github.com/micro/go-micro/registry"
"github.com/micro/go-micro/registry/memory"
"github.com/micro/go-micro/selector"
pgrpc "google.golang.org/grpc"
pb "google.golang.org/grpc/examples/helloworld/helloworld"
)
@@ -36,22 +34,17 @@ func TestGRPCClient(t *testing.T) {
go s.Serve(l)
defer s.Stop()
parts := strings.Split(l.Addr().String(), ":")
port, _ := strconv.Atoi(parts[len(parts)-1])
addr := strings.Join(parts[:len(parts)-1], ":")
// create mock registry
r := memory.NewRegistry()
// register service
r.Register(&registry.Service{
Name: "test",
Name: "helloworld",
Version: "test",
Nodes: []*registry.Node{
&registry.Node{
Id: "test-1",
Address: addr,
Port: port,
Address: l.Addr().String(),
},
},
})
@@ -73,7 +66,7 @@ func TestGRPCClient(t *testing.T) {
}
for _, method := range testMethods {
req := c.NewRequest("test", method, &pb.HelloRequest{
req := c.NewRequest("helloworld", method, &pb.HelloRequest{
Name: "John",
})

View File

@@ -4,13 +4,13 @@ import (
"github.com/micro/go-micro/client"
)
type grpcPublication struct {
type grpcEvent struct {
topic string
contentType string
payload interface{}
}
func newGRPCPublication(topic string, payload interface{}, contentType string, opts ...client.MessageOption) client.Message {
func newGRPCEvent(topic string, payload interface{}, contentType string, opts ...client.MessageOption) client.Message {
var options client.MessageOptions
for _, o := range opts {
o(&options)
@@ -20,21 +20,21 @@ func newGRPCPublication(topic string, payload interface{}, contentType string, o
contentType = options.ContentType
}
return &grpcPublication{
return &grpcEvent{
payload: payload,
topic: topic,
contentType: contentType,
}
}
func (g *grpcPublication) ContentType() string {
func (g *grpcEvent) ContentType() string {
return g.contentType
}
func (g *grpcPublication) Topic() string {
func (g *grpcEvent) Topic() string {
return g.topic
}
func (g *grpcPublication) Payload() interface{} {
func (g *grpcEvent) Payload() interface{} {
return g.payload
}

View File

@@ -2,7 +2,6 @@ package grpc
import (
"fmt"
"reflect"
"strings"
"github.com/micro/go-micro/client"
@@ -15,32 +14,28 @@ type grpcRequest struct {
contentType string
request interface{}
opts client.RequestOptions
codec codec.Codec
}
func methodToGRPC(method string, request interface{}) string {
// service Struct.Method /service.Struct/Method
func methodToGRPC(service, method string) string {
// no method or already grpc method
if len(method) == 0 || method[0] == '/' {
return method
}
// can't operate on nil request
t := reflect.TypeOf(request)
if t == nil {
return method
}
// dereference
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
// get package name
pParts := strings.Split(t.PkgPath(), "/")
pkg := pParts[len(pParts)-1]
// assume method is Foo.Bar
mParts := strings.Split(method, ".")
if len(mParts) != 2 {
return method
}
if len(service) == 0 {
return fmt.Sprintf("/%s/%s", mParts[0], mParts[1])
}
// return /pkg.Foo/Bar
return fmt.Sprintf("/%s.%s/%s", pkg, mParts[0], mParts[1])
return fmt.Sprintf("/%s.%s/%s", service, mParts[0], mParts[1])
}
func newGRPCRequest(service, method string, request interface{}, contentType string, reqOpts ...client.RequestOption) client.Request {
@@ -80,7 +75,7 @@ func (g *grpcRequest) Endpoint() string {
}
func (g *grpcRequest) Codec() codec.Writer {
return nil
return g.codec
}
func (g *grpcRequest) Body() interface{} {

View File

@@ -2,45 +2,38 @@ package grpc
import (
"testing"
pb "google.golang.org/grpc/examples/helloworld/helloworld"
)
func TestMethodToGRPC(t *testing.T) {
testData := []struct {
service string
method string
expect string
request interface{}
}{
{
"helloworld",
"Greeter.SayHello",
"/helloworld.Greeter/SayHello",
new(pb.HelloRequest),
},
{
"helloworld",
"/helloworld.Greeter/SayHello",
"/helloworld.Greeter/SayHello",
new(pb.HelloRequest),
},
{
"",
"/helloworld.Greeter/SayHello",
"/helloworld.Greeter/SayHello",
},
{
"",
"Greeter.SayHello",
"/helloworld.Greeter/SayHello",
pb.HelloRequest{},
},
{
"/helloworld.Greeter/SayHello",
"/helloworld.Greeter/SayHello",
pb.HelloRequest{},
},
{
"Greeter.SayHello",
"Greeter.SayHello",
nil,
"/Greeter/SayHello",
},
}
for _, d := range testData {
method := methodToGRPC(d.method, d.request)
method := methodToGRPC(d.service, d.method)
if method != d.expect {
t.Fatalf("expected %s got %s", d.expect, method)
}

44
client/grpc/response.go Normal file
View File

@@ -0,0 +1,44 @@
package grpc
import (
"strings"
"github.com/micro/go-micro/codec"
"github.com/micro/go-micro/codec/bytes"
"google.golang.org/grpc"
"google.golang.org/grpc/encoding"
)
type response struct {
conn *grpc.ClientConn
stream grpc.ClientStream
codec encoding.Codec
gcodec codec.Codec
}
// Read the response
func (r *response) Codec() codec.Reader {
return r.gcodec
}
// read the header
func (r *response) Header() map[string]string {
md, err := r.stream.Header()
if err != nil {
return map[string]string{}
}
hdr := make(map[string]string)
for k, v := range md {
hdr[k] = strings.Join(v, ",")
}
return hdr
}
// Read the undecoded response
func (r *response) Read() ([]byte, error) {
f := &bytes.Frame{}
if err := r.gcodec.ReadBody(f); err != nil {
return nil, err
}
return f.Data, nil
}

View File

@@ -12,11 +12,12 @@ import (
// Implements the streamer interface
type grpcStream struct {
sync.RWMutex
err error
conn *grpc.ClientConn
request client.Request
stream grpc.ClientStream
context context.Context
err error
conn *grpc.ClientConn
stream grpc.ClientStream
request client.Request
response client.Response
context context.Context
}
func (g *grpcStream) Context() context.Context {
@@ -28,7 +29,7 @@ func (g *grpcStream) Request() client.Request {
}
func (g *grpcStream) Response() client.Response {
return nil
return g.response
}
func (g *grpcStream) Send(msg interface{}) error {

View File

@@ -1,5 +1,5 @@
// Package rpc provides an rpc client
package rpc
// Package mucp provides an mucp client
package mucp
import (
"github.com/micro/go-micro/client"

View File

@@ -5,9 +5,9 @@ import (
"time"
"github.com/micro/go-micro/broker"
"github.com/micro/go-micro/client/selector"
"github.com/micro/go-micro/codec"
"github.com/micro/go-micro/registry"
"github.com/micro/go-micro/selector"
"github.com/micro/go-micro/transport"
)
@@ -43,8 +43,8 @@ type Options struct {
type CallOptions struct {
SelectOptions []selector.SelectOption
// Address of remote host
Address string
// Address of remote hosts
Address []string
// Backoff func
Backoff BackoffFunc
// Check if retriable func
@@ -245,8 +245,8 @@ func WithExchange(e string) PublishOption {
}
}
// WithAddress sets the remote address to use rather than using service discovery
func WithAddress(a string) CallOption {
// WithAddress sets the remote addresses to use rather than using service discovery
func WithAddress(a ...string) CallOption {
return func(o *CallOptions) {
o.Address = a
}

114
client/pool/default.go Normal file
View File

@@ -0,0 +1,114 @@
package pool
import (
"sync"
"time"
"github.com/google/uuid"
"github.com/micro/go-micro/transport"
)
type pool struct {
size int
ttl time.Duration
tr transport.Transport
sync.Mutex
conns map[string][]*poolConn
}
type poolConn struct {
transport.Client
id string
created time.Time
}
func newPool(options Options) *pool {
return &pool{
size: options.Size,
tr: options.Transport,
ttl: options.TTL,
conns: make(map[string][]*poolConn),
}
}
func (p *pool) Close() error {
p.Lock()
for k, c := range p.conns {
for _, conn := range c {
conn.Client.Close()
}
delete(p.conns, k)
}
p.Unlock()
return nil
}
// NoOp the Close since we manage it
func (p *poolConn) Close() error {
return nil
}
func (p *poolConn) Id() string {
return p.id
}
func (p *poolConn) Created() time.Time {
return p.created
}
func (p *pool) Get(addr string, opts ...transport.DialOption) (Conn, error) {
p.Lock()
conns := p.conns[addr]
// while we have conns check age and then return one
// otherwise we'll create a new conn
for len(conns) > 0 {
conn := conns[len(conns)-1]
conns = conns[:len(conns)-1]
p.conns[addr] = conns
// if conn is old kill it and move on
if d := time.Since(conn.Created()); d > p.ttl {
conn.Client.Close()
continue
}
// we got a good conn, lets unlock and return it
p.Unlock()
return conn, nil
}
p.Unlock()
// create new conn
c, err := p.tr.Dial(addr, opts...)
if err != nil {
return nil, err
}
return &poolConn{
Client: c,
id: uuid.New().String(),
created: time.Now(),
}, nil
}
func (p *pool) Release(conn Conn, err error) error {
// don't store the conn if it has errored
if err != nil {
return conn.(*poolConn).Client.Close()
}
// otherwise put it back for reuse
p.Lock()
conns := p.conns[conn.Remote()]
if len(conns) >= p.size {
p.Unlock()
return conn.(*poolConn).Client.Close()
}
p.conns[conn.Remote()] = append(conns, conn.(*poolConn))
p.Unlock()
return nil
}

View File

@@ -1,4 +1,4 @@
package client
package pool
import (
"testing"
@@ -9,12 +9,17 @@ import (
)
func testPool(t *testing.T, size int, ttl time.Duration) {
// zero pool
p := newPool(size, ttl)
// mock transport
tr := memory.NewTransport()
options := Options{
TTL: ttl,
Size: size,
Transport: tr,
}
// zero pool
p := newPool(options)
// listen
l, err := tr.Listen(":0")
if err != nil {
@@ -43,7 +48,7 @@ func testPool(t *testing.T, size int, ttl time.Duration) {
for i := 0; i < 10; i++ {
// get a conn
c, err := p.getConn(l.Addr(), tr)
c, err := p.Get(l.Addr())
if err != nil {
t.Fatal(err)
}
@@ -67,7 +72,7 @@ func testPool(t *testing.T, size int, ttl time.Duration) {
}
// release the conn
p.release(l.Addr(), c, nil)
p.Release(c, nil)
p.Lock()
if i := len(p.conns[l.Addr()]); i > size {
@@ -78,7 +83,7 @@ func testPool(t *testing.T, size int, ttl time.Duration) {
}
}
func TestRPCPool(t *testing.T) {
func TestClientPool(t *testing.T) {
testPool(t, 0, time.Minute)
testPool(t, 2, time.Minute)
}

33
client/pool/options.go Normal file
View File

@@ -0,0 +1,33 @@
package pool
import (
"time"
"github.com/micro/go-micro/transport"
)
type Options struct {
Transport transport.Transport
TTL time.Duration
Size int
}
type Option func(*Options)
func Size(i int) Option {
return func(o *Options) {
o.Size = i
}
}
func Transport(t transport.Transport) Option {
return func(o *Options) {
o.Transport = t
}
}
func TTL(t time.Duration) Option {
return func(o *Options) {
o.TTL = t
}
}

35
client/pool/pool.go Normal file
View File

@@ -0,0 +1,35 @@
// Package pool is a connection pool
package pool
import (
"time"
"github.com/micro/go-micro/transport"
)
// Pool is an interface for connection pooling
type Pool interface {
// Close the pool
Close() error
// Get a connection
Get(addr string, opts ...transport.DialOption) (Conn, error)
// Releaes the connection
Release(c Conn, status error) error
}
type Conn interface {
// unique id of connection
Id() string
// time it was created
Created() time.Time
// embedded connection
transport.Client
}
func NewPool(opts ...Option) Pool {
var options Options
for _, o := range opts {
o(&options)
}
return newPool(options)
}

View File

@@ -0,0 +1,203 @@
// Code generated by protoc-gen-micro. DO NOT EDIT.
// source: micro/go-micro/client/proto/client.proto
package go_micro_client
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 Micro service
type MicroService interface {
// Call allows a single request to be made
Call(ctx context.Context, in *Request, opts ...client.CallOption) (*Response, error)
// Stream is a bidirectional stream
Stream(ctx context.Context, opts ...client.CallOption) (Micro_StreamService, error)
// Publish publishes a message and returns an empty Message
Publish(ctx context.Context, in *Message, opts ...client.CallOption) (*Message, error)
}
type microService struct {
c client.Client
name string
}
func NewMicroService(name string, c client.Client) MicroService {
if c == nil {
c = client.NewClient()
}
if len(name) == 0 {
name = "go.micro.client"
}
return &microService{
c: c,
name: name,
}
}
func (c *microService) Call(ctx context.Context, in *Request, opts ...client.CallOption) (*Response, error) {
req := c.c.NewRequest(c.name, "Micro.Call", in)
out := new(Response)
err := c.c.Call(ctx, req, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *microService) Stream(ctx context.Context, opts ...client.CallOption) (Micro_StreamService, error) {
req := c.c.NewRequest(c.name, "Micro.Stream", &Request{})
stream, err := c.c.Stream(ctx, req, opts...)
if err != nil {
return nil, err
}
return &microServiceStream{stream}, nil
}
type Micro_StreamService interface {
SendMsg(interface{}) error
RecvMsg(interface{}) error
Close() error
Send(*Request) error
Recv() (*Response, error)
}
type microServiceStream struct {
stream client.Stream
}
func (x *microServiceStream) Close() error {
return x.stream.Close()
}
func (x *microServiceStream) SendMsg(m interface{}) error {
return x.stream.Send(m)
}
func (x *microServiceStream) RecvMsg(m interface{}) error {
return x.stream.Recv(m)
}
func (x *microServiceStream) Send(m *Request) error {
return x.stream.Send(m)
}
func (x *microServiceStream) Recv() (*Response, error) {
m := new(Response)
err := x.stream.Recv(m)
if err != nil {
return nil, err
}
return m, nil
}
func (c *microService) Publish(ctx context.Context, in *Message, opts ...client.CallOption) (*Message, error) {
req := c.c.NewRequest(c.name, "Micro.Publish", in)
out := new(Message)
err := c.c.Call(ctx, req, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// Server API for Micro service
type MicroHandler interface {
// Call allows a single request to be made
Call(context.Context, *Request, *Response) error
// Stream is a bidirectional stream
Stream(context.Context, Micro_StreamStream) error
// Publish publishes a message and returns an empty Message
Publish(context.Context, *Message, *Message) error
}
func RegisterMicroHandler(s server.Server, hdlr MicroHandler, opts ...server.HandlerOption) error {
type micro interface {
Call(ctx context.Context, in *Request, out *Response) error
Stream(ctx context.Context, stream server.Stream) error
Publish(ctx context.Context, in *Message, out *Message) error
}
type Micro struct {
micro
}
h := &microHandler{hdlr}
return s.Handle(s.NewHandler(&Micro{h}, opts...))
}
type microHandler struct {
MicroHandler
}
func (h *microHandler) Call(ctx context.Context, in *Request, out *Response) error {
return h.MicroHandler.Call(ctx, in, out)
}
func (h *microHandler) Stream(ctx context.Context, stream server.Stream) error {
return h.MicroHandler.Stream(ctx, &microStreamStream{stream})
}
type Micro_StreamStream interface {
SendMsg(interface{}) error
RecvMsg(interface{}) error
Close() error
Send(*Response) error
Recv() (*Request, error)
}
type microStreamStream struct {
stream server.Stream
}
func (x *microStreamStream) Close() error {
return x.stream.Close()
}
func (x *microStreamStream) SendMsg(m interface{}) error {
return x.stream.Send(m)
}
func (x *microStreamStream) RecvMsg(m interface{}) error {
return x.stream.Recv(m)
}
func (x *microStreamStream) Send(m *Response) error {
return x.stream.Send(m)
}
func (x *microStreamStream) Recv() (*Request, error) {
m := new(Request)
if err := x.stream.Recv(m); err != nil {
return nil, err
}
return m, nil
}
func (h *microHandler) Publish(ctx context.Context, in *Message, out *Message) error {
return h.MicroHandler.Publish(ctx, in, out)
}

388
client/proto/client.pb.go Normal file
View File

@@ -0,0 +1,388 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: micro/go-micro/client/proto/client.proto
package go_micro_client
import (
context "context"
fmt "fmt"
proto "github.com/golang/protobuf/proto"
grpc "google.golang.org/grpc"
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.ProtoPackageIsVersion3 // please upgrade the proto package
type Request struct {
Service string `protobuf:"bytes,1,opt,name=service,proto3" json:"service,omitempty"`
Endpoint string `protobuf:"bytes,2,opt,name=endpoint,proto3" json:"endpoint,omitempty"`
ContentType string `protobuf:"bytes,3,opt,name=content_type,json=contentType,proto3" json:"content_type,omitempty"`
Body []byte `protobuf:"bytes,4,opt,name=body,proto3" json:"body,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_7d733ae29171347b, []int{0}
}
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 (m *Request) XXX_Merge(src proto.Message) {
xxx_messageInfo_Request.Merge(m, 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) GetService() string {
if m != nil {
return m.Service
}
return ""
}
func (m *Request) GetEndpoint() string {
if m != nil {
return m.Endpoint
}
return ""
}
func (m *Request) GetContentType() string {
if m != nil {
return m.ContentType
}
return ""
}
func (m *Request) GetBody() []byte {
if m != nil {
return m.Body
}
return nil
}
type Response struct {
Body []byte `protobuf:"bytes,1,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_7d733ae29171347b, []int{1}
}
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 (m *Response) XXX_Merge(src proto.Message) {
xxx_messageInfo_Response.Merge(m, 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) GetBody() []byte {
if m != nil {
return m.Body
}
return nil
}
type Message struct {
Topic string `protobuf:"bytes,1,opt,name=topic,proto3" json:"topic,omitempty"`
ContentType string `protobuf:"bytes,2,opt,name=content_type,json=contentType,proto3" json:"content_type,omitempty"`
Body []byte `protobuf:"bytes,3,opt,name=body,proto3" json:"body,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *Message) Reset() { *m = Message{} }
func (m *Message) String() string { return proto.CompactTextString(m) }
func (*Message) ProtoMessage() {}
func (*Message) Descriptor() ([]byte, []int) {
return fileDescriptor_7d733ae29171347b, []int{2}
}
func (m *Message) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_Message.Unmarshal(m, b)
}
func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_Message.Marshal(b, m, deterministic)
}
func (m *Message) XXX_Merge(src proto.Message) {
xxx_messageInfo_Message.Merge(m, src)
}
func (m *Message) XXX_Size() int {
return xxx_messageInfo_Message.Size(m)
}
func (m *Message) XXX_DiscardUnknown() {
xxx_messageInfo_Message.DiscardUnknown(m)
}
var xxx_messageInfo_Message proto.InternalMessageInfo
func (m *Message) GetTopic() string {
if m != nil {
return m.Topic
}
return ""
}
func (m *Message) GetContentType() string {
if m != nil {
return m.ContentType
}
return ""
}
func (m *Message) GetBody() []byte {
if m != nil {
return m.Body
}
return nil
}
func init() {
proto.RegisterType((*Request)(nil), "go.micro.client.Request")
proto.RegisterType((*Response)(nil), "go.micro.client.Response")
proto.RegisterType((*Message)(nil), "go.micro.client.Message")
}
func init() {
proto.RegisterFile("micro/go-micro/client/proto/client.proto", fileDescriptor_7d733ae29171347b)
}
var fileDescriptor_7d733ae29171347b = []byte{
// 270 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x91, 0x3f, 0x4f, 0xc3, 0x30,
0x10, 0xc5, 0xeb, 0xfe, 0x4b, 0x39, 0x2a, 0x21, 0x9d, 0x18, 0x4c, 0x06, 0x54, 0x32, 0x65, 0xc1,
0x45, 0x30, 0x23, 0x86, 0xce, 0x95, 0x50, 0x40, 0xac, 0x28, 0x71, 0x4f, 0xc1, 0x52, 0x6a, 0x9b,
0xd8, 0xad, 0x94, 0xef, 0xc8, 0x87, 0x42, 0x38, 0x29, 0x45, 0xd0, 0x2e, 0x6c, 0xf7, 0xee, 0x67,
0xbd, 0x3b, 0xbf, 0x83, 0x74, 0xad, 0x64, 0x6d, 0xe6, 0xa5, 0xb9, 0x6e, 0x0b, 0x59, 0x29, 0xd2,
0x7e, 0x6e, 0x6b, 0xe3, 0x77, 0x42, 0x04, 0x81, 0x67, 0xa5, 0x11, 0xe1, 0x8d, 0x68, 0xdb, 0xc9,
0x16, 0xa2, 0x8c, 0xde, 0x37, 0xe4, 0x3c, 0x72, 0x88, 0x1c, 0xd5, 0x5b, 0x25, 0x89, 0xb3, 0x19,
0x4b, 0x4f, 0xb2, 0x9d, 0xc4, 0x18, 0x26, 0xa4, 0x57, 0xd6, 0x28, 0xed, 0x79, 0x3f, 0xa0, 0x6f,
0x8d, 0x57, 0x30, 0x95, 0x46, 0x7b, 0xd2, 0xfe, 0xd5, 0x37, 0x96, 0xf8, 0x20, 0xf0, 0xd3, 0xae,
0xf7, 0xdc, 0x58, 0x42, 0x84, 0x61, 0x61, 0x56, 0x0d, 0x1f, 0xce, 0x58, 0x3a, 0xcd, 0x42, 0x9d,
0x5c, 0xc2, 0x24, 0x23, 0x67, 0x8d, 0x76, 0x7b, 0xce, 0x7e, 0xf0, 0x17, 0x88, 0x96, 0xe4, 0x5c,
0x5e, 0x12, 0x9e, 0xc3, 0xc8, 0x1b, 0xab, 0x64, 0xb7, 0x55, 0x2b, 0xfe, 0xcc, 0xed, 0x1f, 0x9f,
0x3b, 0xd8, 0xfb, 0xde, 0x7e, 0x30, 0x18, 0x2d, 0xbf, 0x02, 0xc0, 0x7b, 0x18, 0x2e, 0xf2, 0xaa,
0x42, 0x2e, 0x7e, 0x65, 0x22, 0xba, 0x40, 0xe2, 0x8b, 0x03, 0xa4, 0x5d, 0x39, 0xe9, 0xe1, 0x02,
0xc6, 0x4f, 0xbe, 0xa6, 0x7c, 0xfd, 0x4f, 0x83, 0x94, 0xdd, 0x30, 0x7c, 0x80, 0xe8, 0x71, 0x53,
0x54, 0xca, 0xbd, 0x1d, 0x70, 0xe9, 0xfe, 0x1f, 0x1f, 0x25, 0x49, 0xaf, 0x18, 0x87, 0xb3, 0xde,
0x7d, 0x06, 0x00, 0x00, 0xff, 0xff, 0xd3, 0x63, 0x94, 0x1a, 0x02, 0x02, 0x00, 0x00,
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion4
// MicroClient is the client API for Micro service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type MicroClient interface {
// Call allows a single request to be made
Call(ctx context.Context, in *Request, opts ...grpc.CallOption) (*Response, error)
// Stream is a bidirectional stream
Stream(ctx context.Context, opts ...grpc.CallOption) (Micro_StreamClient, error)
// Publish publishes a message and returns an empty Message
Publish(ctx context.Context, in *Message, opts ...grpc.CallOption) (*Message, error)
}
type microClient struct {
cc *grpc.ClientConn
}
func NewMicroClient(cc *grpc.ClientConn) MicroClient {
return &microClient{cc}
}
func (c *microClient) Call(ctx context.Context, in *Request, opts ...grpc.CallOption) (*Response, error) {
out := new(Response)
err := c.cc.Invoke(ctx, "/go.micro.client.Micro/Call", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *microClient) Stream(ctx context.Context, opts ...grpc.CallOption) (Micro_StreamClient, error) {
stream, err := c.cc.NewStream(ctx, &_Micro_serviceDesc.Streams[0], "/go.micro.client.Micro/Stream", opts...)
if err != nil {
return nil, err
}
x := &microStreamClient{stream}
return x, nil
}
type Micro_StreamClient interface {
Send(*Request) error
Recv() (*Response, error)
grpc.ClientStream
}
type microStreamClient struct {
grpc.ClientStream
}
func (x *microStreamClient) Send(m *Request) error {
return x.ClientStream.SendMsg(m)
}
func (x *microStreamClient) Recv() (*Response, error) {
m := new(Response)
if err := x.ClientStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
func (c *microClient) Publish(ctx context.Context, in *Message, opts ...grpc.CallOption) (*Message, error) {
out := new(Message)
err := c.cc.Invoke(ctx, "/go.micro.client.Micro/Publish", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// MicroServer is the server API for Micro service.
type MicroServer interface {
// Call allows a single request to be made
Call(context.Context, *Request) (*Response, error)
// Stream is a bidirectional stream
Stream(Micro_StreamServer) error
// Publish publishes a message and returns an empty Message
Publish(context.Context, *Message) (*Message, error)
}
func RegisterMicroServer(s *grpc.Server, srv MicroServer) {
s.RegisterService(&_Micro_serviceDesc, srv)
}
func _Micro_Call_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(Request)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(MicroServer).Call(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/go.micro.client.Micro/Call",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(MicroServer).Call(ctx, req.(*Request))
}
return interceptor(ctx, in, info, handler)
}
func _Micro_Stream_Handler(srv interface{}, stream grpc.ServerStream) error {
return srv.(MicroServer).Stream(&microStreamServer{stream})
}
type Micro_StreamServer interface {
Send(*Response) error
Recv() (*Request, error)
grpc.ServerStream
}
type microStreamServer struct {
grpc.ServerStream
}
func (x *microStreamServer) Send(m *Response) error {
return x.ServerStream.SendMsg(m)
}
func (x *microStreamServer) Recv() (*Request, error) {
m := new(Request)
if err := x.ServerStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
func _Micro_Publish_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(Message)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(MicroServer).Publish(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/go.micro.client.Micro/Publish",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(MicroServer).Publish(ctx, req.(*Message))
}
return interceptor(ctx, in, info, handler)
}
var _Micro_serviceDesc = grpc.ServiceDesc{
ServiceName: "go.micro.client.Micro",
HandlerType: (*MicroServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Call",
Handler: _Micro_Call_Handler,
},
{
MethodName: "Publish",
Handler: _Micro_Publish_Handler,
},
},
Streams: []grpc.StreamDesc{
{
StreamName: "Stream",
Handler: _Micro_Stream_Handler,
ServerStreams: true,
ClientStreams: true,
},
},
Metadata: "micro/go-micro/client/proto/client.proto",
}

30
client/proto/client.proto Normal file
View File

@@ -0,0 +1,30 @@
syntax = "proto3";
package go.micro.client;
// Micro is the micro client interface
service Micro {
// Call allows a single request to be made
rpc Call(Request) returns (Response) {};
// Stream is a bidirectional stream
rpc Stream(stream Request) returns (stream Response) {};
// Publish publishes a message and returns an empty Message
rpc Publish(Message) returns (Message) {};
}
message Request {
string service = 1;
string endpoint = 2;
string content_type = 3;
bytes body = 4;
}
message Response {
bytes body = 1;
}
message Message {
string topic = 1;
string content_type = 2;
bytes body = 3;
}

View File

@@ -1,40 +1,45 @@
package client
import (
"bytes"
"context"
"fmt"
"net"
"os"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/google/uuid"
"github.com/micro/go-micro/broker"
"github.com/micro/go-micro/client/pool"
"github.com/micro/go-micro/client/selector"
"github.com/micro/go-micro/codec"
"github.com/micro/go-micro/errors"
"github.com/micro/go-micro/metadata"
"github.com/micro/go-micro/registry"
"github.com/micro/go-micro/selector"
"github.com/micro/go-micro/transport"
"github.com/micro/go-micro/util/buf"
)
type rpcClient struct {
once sync.Once
opts Options
pool *pool
pool pool.Pool
seq uint64
}
func newRpcClient(opt ...Option) Client {
opts := newOptions(opt...)
p := pool.NewPool(
pool.Size(opts.PoolSize),
pool.TTL(opts.PoolTTL),
pool.Transport(opts.Transport),
)
rc := &rpcClient{
once: sync.Once{},
opts: opts,
pool: newPool(opts.PoolSize, opts.PoolTTL),
pool: p,
seq: 0,
}
@@ -60,9 +65,6 @@ func (r *rpcClient) newCodec(contentType string) (codec.NewCodec, error) {
func (r *rpcClient) call(ctx context.Context, node *registry.Node, req Request, resp interface{}, opts CallOptions) error {
address := node.Address
if node.Port > 0 {
address = fmt.Sprintf("%s:%d", address, node.Port)
}
msg := &transport.Message{
Header: make(map[string]string),
@@ -95,13 +97,13 @@ func (r *rpcClient) call(ctx context.Context, node *registry.Node, req Request,
}
var grr error
c, err := r.pool.getConn(address, r.opts.Transport, transport.WithTimeout(opts.DialTimeout))
c, err := r.pool.Get(address, transport.WithTimeout(opts.DialTimeout))
if err != nil {
return errors.InternalServerError("go.micro.client", "connection error: %v", err)
}
defer func() {
// defer execution of release
r.pool.release(address, c, grr)
r.pool.Release(c, grr)
}()
seq := atomic.LoadUint64(&r.seq)
@@ -160,9 +162,6 @@ func (r *rpcClient) call(ctx context.Context, node *registry.Node, req Request,
func (r *rpcClient) stream(ctx context.Context, node *registry.Node, req Request, opts CallOptions) (Stream, error) {
address := node.Address
if node.Port > 0 {
address = fmt.Sprintf("%s:%d", address, node.Port)
}
msg := &transport.Message{
Header: make(map[string]string),
@@ -253,17 +252,22 @@ func (r *rpcClient) stream(ctx context.Context, node *registry.Node, req Request
func (r *rpcClient) Init(opts ...Option) error {
size := r.opts.PoolSize
ttl := r.opts.PoolTTL
tr := r.opts.Transport
for _, o := range opts {
o(&r.opts)
}
// update pool configuration if the options changed
if size != r.opts.PoolSize || ttl != r.opts.PoolTTL {
r.pool.Lock()
r.pool.size = r.opts.PoolSize
r.pool.ttl = int64(r.opts.PoolTTL.Seconds())
r.pool.Unlock()
if size != r.opts.PoolSize || ttl != r.opts.PoolTTL || tr != r.opts.Transport {
// close existing pool
r.pool.Close()
// create new pool
r.pool = pool.NewPool(
pool.Size(r.opts.PoolSize),
pool.TTL(r.opts.PoolTTL),
pool.Transport(r.opts.Transport),
)
}
return nil
@@ -283,25 +287,26 @@ func (r *rpcClient) next(request Request, opts CallOptions) (selector.Next, erro
// get proxy address
if prx := os.Getenv("MICRO_PROXY_ADDRESS"); len(prx) > 0 {
opts.Address = prx
opts.Address = []string{prx}
}
// return remote address
if len(opts.Address) > 0 {
address := opts.Address
port := 0
nodes := make([]*registry.Node, len(opts.Address))
host, sport, err := net.SplitHostPort(opts.Address)
if err == nil {
address = host
port, _ = strconv.Atoi(sport)
for i, address := range opts.Address {
nodes[i] = &registry.Node{
Address: address,
// Set the protocol
Metadata: map[string]string{
"protocol": "mucp",
},
}
}
// crude return method
return func() (*registry.Node, error) {
return &registry.Node{
Address: address,
Port: port,
}, nil
return nodes[time.Now().Unix()%int64(len(nodes))], nil
}, nil
}
@@ -533,10 +538,13 @@ func (r *rpcClient) Publish(ctx context.Context, msg Message, opts ...PublishOpt
if err != nil {
return errors.InternalServerError("go.micro.client", err.Error())
}
b := &buffer{bytes.NewBuffer(nil)}
// new buffer
b := buf.New(nil)
if err := cf(b).Write(&codec.Message{
Target: topic,
Type: codec.Publication,
Type: codec.Event,
Header: map[string]string{
"Micro-Id": id,
"Micro-Topic": msg.Topic(),
@@ -563,5 +571,5 @@ func (r *rpcClient) NewRequest(service, method string, request interface{}, reqO
}
func (r *rpcClient) String() string {
return "rpc"
return "mucp"
}

View File

@@ -5,24 +5,24 @@ import (
"fmt"
"testing"
"github.com/micro/go-micro/client/selector"
"github.com/micro/go-micro/errors"
"github.com/micro/go-micro/registry"
"github.com/micro/go-micro/registry/memory"
"github.com/micro/go-micro/selector"
)
func newTestRegistry() registry.Registry {
r := memory.NewRegistry()
r.(*memory.Registry).Setup()
return r
reg := r.(*memory.Registry)
reg.Services = testData
return reg
}
func TestCallAddress(t *testing.T) {
var called bool
service := "test.service"
endpoint := "Test.Endpoint"
address := "10.1.10.1"
port := 8080
address := "10.1.10.1:8080"
wrap := func(cf CallFunc) CallFunc {
return func(ctx context.Context, node *registry.Node, req Request, rsp interface{}, opts CallOptions) error {
@@ -40,10 +40,6 @@ func TestCallAddress(t *testing.T) {
return fmt.Errorf("expected address: %s got %s", address, node.Address)
}
if node.Port != port {
return fmt.Errorf("expected address: %d got %d", port, node.Port)
}
// don't do the call
return nil
}
@@ -59,7 +55,7 @@ func TestCallAddress(t *testing.T) {
req := c.NewRequest(service, endpoint, nil)
// test calling remote address
if err := c.Call(context.Background(), req, nil, WithAddress(fmt.Sprintf("%s:%d", address, port))); err != nil {
if err := c.Call(context.Background(), req, nil, WithAddress(address)); err != nil {
t.Fatal("call with address error", err)
}
@@ -113,8 +109,7 @@ func TestCallWrapper(t *testing.T) {
id := "test.1"
service := "test.service"
endpoint := "Test.Endpoint"
address := "10.1.10.1"
port := 8080
address := "10.1.10.1:8080"
wrap := func(cf CallFunc) CallFunc {
return func(ctx context.Context, node *registry.Node, req Request, rsp interface{}, opts CallOptions) error {
@@ -151,7 +146,6 @@ func TestCallWrapper(t *testing.T) {
&registry.Node{
Id: id,
Address: address,
Port: port,
},
},
})

View File

@@ -1,87 +0,0 @@
package client
import (
"sync"
"time"
"github.com/micro/go-micro/transport"
)
type pool struct {
size int
ttl int64
sync.Mutex
conns map[string][]*poolConn
}
type poolConn struct {
transport.Client
created int64
}
func newPool(size int, ttl time.Duration) *pool {
return &pool{
size: size,
ttl: int64(ttl.Seconds()),
conns: make(map[string][]*poolConn),
}
}
// NoOp the Close since we manage it
func (p *poolConn) Close() error {
return nil
}
func (p *pool) getConn(addr string, tr transport.Transport, opts ...transport.DialOption) (*poolConn, error) {
p.Lock()
conns := p.conns[addr]
now := time.Now().Unix()
// while we have conns check age and then return one
// otherwise we'll create a new conn
for len(conns) > 0 {
conn := conns[len(conns)-1]
conns = conns[:len(conns)-1]
p.conns[addr] = conns
// if conn is old kill it and move on
if d := now - conn.created; d > p.ttl {
conn.Client.Close()
continue
}
// we got a good conn, lets unlock and return it
p.Unlock()
return conn, nil
}
p.Unlock()
// create new conn
c, err := tr.Dial(addr, opts...)
if err != nil {
return nil, err
}
return &poolConn{c, time.Now().Unix()}, nil
}
func (p *pool) release(addr string, conn *poolConn, err error) {
// don't store the conn if it has errored
if err != nil {
conn.Client.Close()
return
}
// otherwise put it back for reuse
p.Lock()
conns := p.conns[addr]
if len(conns) >= p.size {
p.Unlock()
conn.Client.Close()
return
}
p.conns[addr] = append(conns, conn)
p.Unlock()
}

View File

@@ -0,0 +1,47 @@
package selector
import (
"github.com/micro/go-micro/registry"
)
var (
// mock data
testData = map[string][]*registry.Service{
"foo": []*registry.Service{
{
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",
},
},
},
},
}
)

View File

@@ -10,7 +10,8 @@ func TestRegistrySelector(t *testing.T) {
counts := map[string]int{}
r := memory.NewRegistry()
r.(*memory.Registry).Setup()
rg := r.(*memory.Registry)
rg.Services = testData
cache := NewSelector(Registry(r))
next, err := cache.Select("foo")

View File

@@ -2,11 +2,12 @@
package dns
import (
"fmt"
"net"
"strconv"
"github.com/micro/go-micro/client/selector"
"github.com/micro/go-micro/registry"
"github.com/micro/go-micro/selector"
)
type dnsSelector struct {
@@ -66,8 +67,7 @@ func (d *dnsSelector) Select(service string, opts ...selector.SelectOption) (sel
for _, node := range srv {
nodes = append(nodes, &registry.Node{
Id: node.Target,
Address: node.Target,
Port: int(node.Port),
Address: fmt.Sprintf("%s:%d", node.Target, node.Port),
})
}

View File

@@ -4,7 +4,7 @@ import (
"context"
"time"
"github.com/micro/go-micro/selector"
"github.com/micro/go-micro/client/selector"
)
// Set the registry cache ttl

View File

@@ -2,7 +2,7 @@
package registry
import (
"github.com/micro/go-micro/selector"
"github.com/micro/go-micro/client/selector"
)
// NewSelector returns a new registry selector

View File

@@ -0,0 +1,272 @@
// Package router is a network/router selector
package router
import (
"context"
"os"
"sort"
"sync"
"github.com/micro/go-micro/client"
"github.com/micro/go-micro/client/selector"
"github.com/micro/go-micro/network/router"
pb "github.com/micro/go-micro/network/router/proto"
"github.com/micro/go-micro/registry"
)
type routerSelector struct {
opts selector.Options
// the router
r router.Router
// the client we have
c client.Client
// the client for the remote router
rs pb.RouterService
// name of the router
name string
// address of the remote router
addr string
// whether to use the remote router
remote bool
}
type clientKey struct{}
type routerKey struct{}
// getRoutes returns the routes whether they are remote or local
func (r *routerSelector) getRoutes(service string) ([]router.Route, error) {
if !r.remote {
// lookup router for routes for the service
return r.r.Lookup(router.NewQuery(
router.QueryService(service),
))
}
// lookup the remote router
var addrs []string
// set the remote address if specified
if len(r.addr) > 0 {
addrs = append(addrs, r.addr)
} else {
// we have a name so we need to check the registry
services, err := r.c.Options().Registry.GetService(r.name)
if err != nil {
return nil, err
}
for _, service := range services {
for _, node := range service.Nodes {
addrs = append(addrs, node.Address)
}
}
}
// no router addresses available
if len(addrs) == 0 {
return nil, selector.ErrNoneAvailable
}
var pbRoutes *pb.LookupResponse
var err error
// TODO: implement backoff and retries
for _, addr := range addrs {
// call the router
pbRoutes, err = r.rs.Lookup(context.Background(), &pb.LookupRequest{
Query: &pb.Query{
Service: service,
},
}, client.WithAddress(addr))
if err != nil {
continue
}
break
}
// errored out
if err != nil {
return nil, err
}
// no routes
if pbRoutes == nil {
return nil, selector.ErrNoneAvailable
}
var routes []router.Route
// convert from pb to []*router.Route
for _, r := range pbRoutes.Routes {
routes = append(routes, router.Route{
Service: r.Service,
Address: r.Address,
Gateway: r.Gateway,
Network: r.Network,
Link: r.Link,
Metric: int(r.Metric),
})
}
return routes, nil
}
func (r *routerSelector) Init(opts ...selector.Option) error {
// no op
return nil
}
func (r *routerSelector) Options() selector.Options {
return r.opts
}
func (r *routerSelector) Select(service string, opts ...selector.SelectOption) (selector.Next, error) {
// TODO: pull routes asynchronously and cache
routes, err := r.getRoutes(service)
if err != nil {
return nil, err
}
// no routes return not found error
if len(routes) == 0 {
return nil, selector.ErrNotFound
}
// TODO: apply filters by pseudo constructing service
// sort the routes based on metric
sort.Slice(routes, func(i, j int) bool {
return routes[i].Metric < routes[j].Metric
})
// roundrobin assuming routes are in metric preference order
var i int
var mtx sync.Mutex
return func() (*registry.Node, error) {
// get index and increment counter with every call to next
mtx.Lock()
idx := i
i++
mtx.Unlock()
// get route based on idx
route := routes[idx%len(routes)]
// defaults to gateway and no port
address := route.Address
if len(route.Gateway) > 0 {
address = route.Gateway
}
// return as a node
return &registry.Node{
// TODO: add id and metadata if we can
Address: address,
}, nil
}, nil
}
func (r *routerSelector) Mark(service string, node *registry.Node, err error) {
// TODO: pass back metrics or information to the router
return
}
func (r *routerSelector) Reset(service string) {
// TODO: reset the metrics or information at the router
return
}
func (r *routerSelector) Close() error {
// stop the router advertisements
return r.r.Stop()
}
func (r *routerSelector) String() string {
return "router"
}
// NewSelector returns a new router based selector
func NewSelector(opts ...selector.Option) selector.Selector {
options := selector.Options{
Context: context.Background(),
}
for _, o := range opts {
o(&options)
}
// set default registry if not set
if options.Registry == nil {
options.Registry = registry.DefaultRegistry
}
// try get router from the context
r, ok := options.Context.Value(routerKey{}).(router.Router)
if !ok {
// TODO: Use router.DefaultRouter?
r = router.NewRouter(
router.Registry(options.Registry),
)
}
// try get client from the context
c, ok := options.Context.Value(clientKey{}).(client.Client)
if !ok {
c = client.DefaultClient
}
// get the router from env vars if its a remote service
remote := true
routerName := os.Getenv("MICRO_ROUTER")
routerAddress := os.Getenv("MICRO_ROUTER_ADDRESS")
// start the router advertisements if we're running it locally
if len(routerName) == 0 && len(routerAddress) == 0 {
go r.Advertise()
remote = false
}
return &routerSelector{
opts: options,
// set the internal router
r: r,
// set the client
c: c,
// set the router client
rs: pb.NewRouterService(routerName, c),
// name of the router
name: routerName,
// address of router
addr: routerAddress,
// let ourselves know to use the remote router
remote: remote,
}
}
// WithClient sets the client for the request
func WithClient(c client.Client) selector.Option {
return func(o *selector.Options) {
if o.Context == nil {
o.Context = context.Background()
}
o.Context = context.WithValue(o.Context, clientKey{}, c)
}
}
// WithRouter sets the router as an option
func WithRouter(r router.Router) selector.Option {
return func(o *selector.Options) {
if o.Context == nil {
o.Context = context.Background()
}
o.Context = context.WithValue(o.Context, routerKey{}, r)
}
}

View File

@@ -2,11 +2,8 @@
package static
import (
"net"
"strconv"
"github.com/micro/go-micro/client/selector"
"github.com/micro/go-micro/registry"
"github.com/micro/go-micro/selector"
)
// staticSelector is a static selector
@@ -26,20 +23,10 @@ func (s *staticSelector) Options() selector.Options {
}
func (s *staticSelector) Select(service string, opts ...selector.SelectOption) (selector.Next, error) {
var port int
addr, pt, err := net.SplitHostPort(service)
if err != nil {
addr = service
port = 0
} else {
port, _ = strconv.Atoi(pt)
}
return func() (*registry.Node, error) {
return &registry.Node{
Id: service,
Address: addr,
Port: port,
Address: service,
}, nil
}, nil
}

View File

@@ -14,13 +14,11 @@ func TestStrategies(t *testing.T) {
Nodes: []*registry.Node{
&registry.Node{
Id: "test1-1",
Address: "10.0.0.1",
Port: 1001,
Address: "10.0.0.1:1001",
},
&registry.Node{
Id: "test1-2",
Address: "10.0.0.2",
Port: 1002,
Address: "10.0.0.2:1002",
},
},
},
@@ -30,13 +28,11 @@ func TestStrategies(t *testing.T) {
Nodes: []*registry.Node{
&registry.Node{
Id: "test1-3",
Address: "10.0.0.3",
Port: 1003,
Address: "10.0.0.3:1003",
},
&registry.Node{
Id: "test1-4",
Address: "10.0.0.4",
Port: 1004,
Address: "10.0.0.4:1004",
},
},
},

View File

@@ -9,7 +9,7 @@ const (
Error MessageType = iota
Request
Response
Publication
Event
)
type MessageType int

View File

@@ -5,6 +5,8 @@ import (
"encoding/json"
"io"
"github.com/golang/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
"github.com/micro/go-micro/codec"
)
@@ -22,6 +24,9 @@ func (c *Codec) ReadBody(b interface{}) error {
if b == nil {
return nil
}
if pb, ok := b.(proto.Message); ok {
return jsonpb.UnmarshalNext(c.Decoder, pb)
}
return c.Decoder.Decode(b)
}

View File

@@ -2,6 +2,9 @@ package json
import (
"encoding/json"
"github.com/golang/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
)
type Marshaler struct{}
@@ -11,6 +14,9 @@ func (j Marshaler) Marshal(v interface{}) ([]byte, error) {
}
func (j Marshaler) Unmarshal(d []byte, v interface{}) error {
if pb, ok := v.(proto.Message); ok {
return jsonpb.UnmarshalString(string(d), pb)
}
return json.Unmarshal(d, v)
}

View File

@@ -33,7 +33,7 @@ func (j *jsonCodec) Write(m *codec.Message, b interface{}) error {
return j.c.Write(m, b)
case codec.Response, codec.Error:
return j.s.Write(m, b)
case codec.Publication:
case codec.Event:
data, err := json.Marshal(b)
if err != nil {
return err
@@ -54,7 +54,7 @@ func (j *jsonCodec) ReadHeader(m *codec.Message, mt codec.MessageType) error {
return j.s.ReadHeader(m)
case codec.Response:
return j.c.ReadHeader(m)
case codec.Publication:
case codec.Event:
_, err := io.Copy(j.buf, j.rwc)
return err
default:
@@ -69,7 +69,7 @@ func (j *jsonCodec) ReadBody(b interface{}) error {
return j.s.ReadBody(b)
case codec.Response:
return j.c.ReadBody(b)
case codec.Publication:
case codec.Event:
if b != nil {
return json.Unmarshal(j.buf.Bytes(), b)
}

View File

@@ -99,7 +99,7 @@ func (c *protoCodec) Write(m *codec.Message, b interface{}) error {
return err
}
}
case codec.Publication:
case codec.Event:
data, err := proto.Marshal(b.(proto.Message))
if err != nil {
return err
@@ -141,7 +141,7 @@ func (c *protoCodec) ReadHeader(m *codec.Message, mt codec.MessageType) error {
m.Method = rtmp.GetServiceMethod()
m.Id = fmt.Sprintf("%d", rtmp.GetSeq())
m.Error = rtmp.GetError()
case codec.Publication:
case codec.Event:
_, err := io.Copy(c.buf, c.rwc)
return err
default:
@@ -159,7 +159,7 @@ func (c *protoCodec) ReadBody(b interface{}) error {
if err != nil {
return err
}
case codec.Publication:
case codec.Event:
data = c.buf.Bytes()
default:
return fmt.Errorf("Unrecognised message type: %v", c.mt)

View File

@@ -30,6 +30,9 @@ func (c *Codec) ReadBody(b interface{}) error {
}
switch b.(type) {
case *string:
v := b.(*string)
*v = string(buf)
case *[]byte:
v := b.(*[]byte)
*v = buf
@@ -51,6 +54,12 @@ func (c *Codec) Write(m *codec.Message, b interface{}) error {
case *[]byte:
ve := b.(*[]byte)
v = *ve
case *string:
ve := b.(*string)
v = []byte(*ve)
case string:
ve := b.(string)
v = []byte(ve)
case []byte:
v = b.([]byte)
default:
@@ -65,7 +74,7 @@ func (c *Codec) Close() error {
}
func (c *Codec) String() string {
return "bytes"
return "text"
}
func NewCodec(c io.ReadWriteCloser) codec.Codec {

47
common_test.go Normal file
View File

@@ -0,0 +1,47 @@
package micro
import (
"github.com/micro/go-micro/registry"
)
var (
// mock data
testData = map[string][]*registry.Service{
"foo": []*registry.Service{
{
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",
},
},
},
},
}
)

View File

@@ -1,6 +1,6 @@
# Config [![GoDoc](https://godoc.org/github.com/micro/go-micro/config?status.svg)](https://godoc.org/github.com/micro/go-micro/config)
Go Config is a pluggable dynamic config library.
Config is a pluggable dynamic config package
Most config in applications are statically configured or include complex logic to load from multiple sources.
Go Config makes this easy, pluggable and mergeable. You'll never have to deal with config in the same way again.

View File

@@ -11,7 +11,11 @@ import (
"github.com/micro/cli"
"github.com/micro/go-micro/client"
cgrpc "github.com/micro/go-micro/client/grpc"
cmucp "github.com/micro/go-micro/client/mucp"
"github.com/micro/go-micro/server"
sgrpc "github.com/micro/go-micro/server/grpc"
smucp "github.com/micro/go-micro/server/mucp"
"github.com/micro/go-micro/util/log"
// brokers
@@ -28,9 +32,10 @@ import (
rmem "github.com/micro/go-micro/registry/memory"
// selectors
"github.com/micro/go-micro/selector"
"github.com/micro/go-micro/selector/dns"
"github.com/micro/go-micro/selector/static"
"github.com/micro/go-micro/client/selector"
"github.com/micro/go-micro/client/selector/dns"
"github.com/micro/go-micro/client/selector/router"
"github.com/micro/go-micro/client/selector/static"
// transports
"github.com/micro/go-micro/transport"
@@ -176,7 +181,9 @@ var (
}
DefaultClients = map[string]func(...client.Option) client.Client{
"rpc": client.NewClient,
"rpc": client.NewClient,
"mucp": cmucp.NewClient,
"grpc": cgrpc.NewClient,
}
DefaultRegistries = map[string]func(...registry.Option) registry.Registry{
@@ -190,11 +197,14 @@ var (
"default": selector.NewSelector,
"dns": dns.NewSelector,
"cache": selector.NewSelector,
"router": router.NewSelector,
"static": static.NewSelector,
}
DefaultServers = map[string]func(...server.Option) server.Server{
"rpc": server.NewServer,
"rpc": server.NewServer,
"mucp": smucp.NewServer,
"grpc": sgrpc.NewServer,
}
DefaultTransports = map[string]func(...transport.Option) transport.Transport{

View File

@@ -5,8 +5,8 @@ import (
"github.com/micro/go-micro/broker"
"github.com/micro/go-micro/client"
"github.com/micro/go-micro/client/selector"
"github.com/micro/go-micro/registry"
"github.com/micro/go-micro/selector"
"github.com/micro/go-micro/server"
"github.com/micro/go-micro/transport"
)

View File

@@ -8,9 +8,25 @@ import (
"testing"
"time"
"github.com/micro/go-micro/config/source/env"
"github.com/micro/go-micro/config/source/file"
)
func createFileForIssue18(t *testing.T, content string) *os.File {
data := []byte(content)
path := filepath.Join(os.TempDir(), fmt.Sprintf("file.%d", time.Now().UnixNano()))
fh, err := os.Create(path)
if err != nil {
t.Error(err)
}
_, err = fh.Write(data)
if err != nil {
t.Error(err)
}
return fh
}
func createFileForTest(t *testing.T) *os.File {
data := []byte(`{"foo": "bar"}`)
path := filepath.Join(os.TempDir(), fmt.Sprintf("file.%d", time.Now().UnixNano()))
@@ -26,7 +42,7 @@ func createFileForTest(t *testing.T) *os.File {
return fh
}
func TestLoadWithGoodFile(t *testing.T) {
func TestConfigLoadWithGoodFile(t *testing.T) {
fh := createFileForTest(t)
path := fh.Name()
defer func() {
@@ -44,7 +60,7 @@ func TestLoadWithGoodFile(t *testing.T) {
}
}
func TestLoadWithInvalidFile(t *testing.T) {
func TestConfigLoadWithInvalidFile(t *testing.T) {
fh := createFileForTest(t)
path := fh.Name()
defer func() {
@@ -68,34 +84,35 @@ func TestLoadWithInvalidFile(t *testing.T) {
}
}
func TestConsul(t *testing.T) {
/*consulSource := consul.NewSource(
// optionally specify consul address; default to localhost:8500
consul.WithAddress("131.150.38.111:8500"),
// optionally specify prefix; defaults to /micro/config
consul.WithPrefix("/project"),
// optionally strip the provided prefix from the keys, defaults to false
consul.StripPrefix(true),
consul.WithDatacenter("dc1"),
consul.WithToken("xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"),
func TestConfigMerge(t *testing.T) {
fh := createFileForIssue18(t, `{
"amqp": {
"host": "rabbit.platform",
"port": 80
},
"handler": {
"exchange": "springCloudBus"
}
}`)
path := fh.Name()
defer func() {
fh.Close()
os.Remove(path)
}()
os.Setenv("AMQP_HOST", "rabbit.testing.com")
conf := NewConfig()
conf.Load(
file.NewSource(
file.WithPath(path),
),
env.NewSource(),
)
// Create new config
conf := NewConfig()
// Load file source
err := conf.Load(consulSource)
if err != nil {
t.Error(err)
return
actualHost := conf.Get("amqp", "host").String("backup")
if actualHost != "rabbit.testing.com" {
t.Fatalf("Expected %v but got %v",
"rabbit.testing.com",
actualHost)
}
m := conf.Map()
t.Log("m: ", m)
v := conf.Get("project", "dc111", "port")
t.Log("v: ", v.Int(13))*/
t.Log("OK")
}

View File

@@ -1,60 +0,0 @@
package config
import (
"fmt"
"os"
"path/filepath"
"testing"
"time"
"github.com/micro/go-micro/config/source/env"
"github.com/micro/go-micro/config/source/file"
)
func createFileForIssue18(t *testing.T, content string) *os.File {
data := []byte(content)
path := filepath.Join(os.TempDir(), fmt.Sprintf("file.%d", time.Now().UnixNano()))
fh, err := os.Create(path)
if err != nil {
t.Error(err)
}
_, err = fh.Write(data)
if err != nil {
t.Error(err)
}
return fh
}
func TestIssue18(t *testing.T) {
fh := createFileForIssue18(t, `{
"amqp": {
"host": "rabbit.platform",
"port": 80
},
"handler": {
"exchange": "springCloudBus"
}
}`)
path := fh.Name()
defer func() {
fh.Close()
os.Remove(path)
}()
os.Setenv("AMQP_HOST", "rabbit.testing.com")
conf := NewConfig()
conf.Load(
file.NewSource(
file.WithPath(path),
),
env.NewSource(),
)
actualHost := conf.Get("amqp", "host").String("backup")
if actualHost != "rabbit.testing.com" {
t.Fatalf("Expected %v but got %v",
"rabbit.testing.com",
actualHost)
}
}

34
config/options/default.go Normal file
View File

@@ -0,0 +1,34 @@
package options
type defaultOptions struct {
opts *Values
}
type stringKey struct{}
func (d *defaultOptions) Init(opts ...Option) error {
if d.opts == nil {
d.opts = new(Values)
}
for _, o := range opts {
if err := d.opts.Option(o); err != nil {
return err
}
}
return nil
}
func (d *defaultOptions) Values() *Values {
return d.opts
}
func (d *defaultOptions) String() string {
if d.opts == nil {
d.opts = new(Values)
}
n, ok := d.opts.Get(stringKey{})
if ok {
return n.(string)
}
return "Values"
}

73
config/options/options.go Normal file
View File

@@ -0,0 +1,73 @@
// Package options provides a way to initialise options
package options
import (
"sync"
)
// Options is used for initialisation
type Options interface {
// Initialise options
Init(...Option) error
// Options returns the current options
Values() *Values
// The name for who these options exist
String() string
}
// Values holds the set of option values and protects them
type Values struct {
sync.RWMutex
values map[interface{}]interface{}
}
// Option gives access to options
type Option func(o *Values) error
// Get a value from options
func (o *Values) Get(k interface{}) (interface{}, bool) {
o.RLock()
defer o.RUnlock()
v, ok := o.values[k]
return v, ok
}
// Set a value in the options
func (o *Values) Set(k, v interface{}) error {
o.Lock()
defer o.Unlock()
if o.values == nil {
o.values = map[interface{}]interface{}{}
}
o.values[k] = v
return nil
}
// SetOption executes an option
func (o *Values) Option(op Option) error {
return op(o)
}
// WithValue allows you to set any value within the options
func WithValue(k, v interface{}) Option {
return func(o *Values) error {
return o.Set(k, v)
}
}
// WithOption gives you the ability to create an option that accesses values
func WithOption(o Option) Option {
return o
}
// String sets the string
func WithString(s string) Option {
return WithValue(stringKey{}, s)
}
// NewOptions returns a new initialiser
func NewOptions(opts ...Option) Options {
o := new(defaultOptions)
o.Init(opts...)
return o
}

View File

@@ -1,39 +1,85 @@
package json
import (
"reflect"
"testing"
"github.com/micro/go-micro/config/source"
)
func TestValues(t *testing.T) {
data := []byte(`{"foo": "bar", "baz": {"bar": "cat"}}`)
emptyStr := ""
testData := []struct {
path []string
value string
csdata []byte
path []string
accepter interface{}
value interface{}
}{
{
[]byte(`{"foo": "bar", "baz": {"bar": "cat"}}`),
[]string{"foo"},
emptyStr,
"bar",
},
{
[]byte(`{"foo": "bar", "baz": {"bar": "cat"}}`),
[]string{"baz", "bar"},
emptyStr,
"cat",
},
}
values, err := newValues(&source.ChangeSet{
Data: data,
})
for idx, test := range testData {
values, err := newValues(&source.ChangeSet{
Data: test.csdata,
})
if err != nil {
t.Fatal(err)
}
if err != nil {
t.Fatal(err)
}
for _, test := range testData {
if v := values.Get(test.path...).String(""); v != test.value {
t.Fatalf("Expected %s got %s for path %v", test.value, v, test.path)
err = values.Get(test.path...).Scan(&test.accepter)
if err != nil {
t.Fatal(err)
}
if test.accepter != test.value {
t.Fatalf("No.%d Expected %v got %v for path %v", idx, test.value, test.accepter, test.path)
}
}
}
func TestStructArray(t *testing.T) {
type T struct {
Foo string
}
emptyTSlice := []T{}
testData := []struct {
csdata []byte
accepter []T
value []T
}{
{
[]byte(`[{"foo": "bar"}]`),
emptyTSlice,
[]T{T{Foo: "bar"}},
},
}
for idx, test := range testData {
values, err := newValues(&source.ChangeSet{
Data: test.csdata,
})
if err != nil {
t.Fatal(err)
}
err = values.Get().Scan(&test.accepter)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(test.accepter, test.value) {
t.Fatalf("No.%d Expected %v got %v", idx, test.value, test.accepter)
}
}
}

View File

@@ -9,7 +9,7 @@ import (
"github.com/imdario/mergo"
"github.com/micro/cli"
"github.com/micro/go-micro/cmd"
"github.com/micro/go-micro/config/cmd"
"github.com/micro/go-micro/config/source"
)

View File

@@ -6,7 +6,7 @@ import (
"testing"
"github.com/micro/cli"
"github.com/micro/go-micro/cmd"
"github.com/micro/go-micro/config/cmd"
"github.com/micro/go-micro/config/source"
)

View File

@@ -74,6 +74,11 @@ func NewSource(opts ...source.Option) source.Source {
// use default config
config := api.DefaultConfig()
// use the consul config passed in the options if any
if co, ok := options.Context.Value(configKey{}).(*api.Config); ok {
config = co
}
// check if there are any addrs
a, ok := options.Context.Value(addressKey{}).(string)
if ok {

View File

@@ -3,6 +3,7 @@ package consul
import (
"context"
"github.com/hashicorp/consul/api"
"github.com/micro/go-micro/config/source"
)
@@ -11,6 +12,7 @@ type prefixKey struct{}
type stripPrefixKey struct{}
type dcKey struct{}
type tokenKey struct{}
type configKey struct{}
// WithAddress sets the consul address
func WithAddress(a string) source.Option {
@@ -61,3 +63,13 @@ func WithToken(p string) source.Option {
o.Context = context.WithValue(o.Context, tokenKey{}, p)
}
}
// WithConfig set consul-specific options
func WithConfig(c *api.Config) source.Option {
return func(o *source.Options) {
if o.Context == nil {
o.Context = context.Background()
}
o.Context = context.WithValue(o.Context, configKey{}, c)
}
}

View File

@@ -8,40 +8,80 @@ import (
"github.com/micro/go-micro/config/encoder"
)
type configValue interface {
Value() interface{}
Decode(encoder.Encoder, []byte) error
}
type configArrayValue struct {
v []interface{}
}
func (a *configArrayValue) Value() interface{} { return a.v }
func (a *configArrayValue) Decode(e encoder.Encoder, b []byte) error {
return e.Decode(b, &a.v)
}
type configMapValue struct {
v map[string]interface{}
}
func (m *configMapValue) Value() interface{} { return m.v }
func (m *configMapValue) Decode(e encoder.Encoder, b []byte) error {
return e.Decode(b, &m.v)
}
func makeMap(e encoder.Encoder, kv api.KVPairs, stripPrefix string) (map[string]interface{}, error) {
data := make(map[string]interface{})
// consul guarantees lexicographic order, so no need to sort
for _, v := range kv {
pathString := strings.TrimPrefix(strings.TrimPrefix(v.Key, stripPrefix), "/")
var val map[string]interface{}
pathString := strings.TrimPrefix(strings.TrimPrefix(v.Key, strings.TrimPrefix(stripPrefix, "/")), "/")
if pathString == "" {
continue
}
var val configValue
var err error
// ensure a valid value is stored at this location
if len(v.Value) > 0 {
if err := e.Decode(v.Value, &val); err != nil {
// try to decode into map value or array value
arrayV := &configArrayValue{v: []interface{}{}}
mapV := &configMapValue{v: map[string]interface{}{}}
switch {
case arrayV.Decode(e, v.Value) == nil:
val = arrayV
case mapV.Decode(e, v.Value) == nil:
val = mapV
default:
return nil, fmt.Errorf("faild decode value. path: %s, error: %s", pathString, err)
}
}
// set target at the root
target := data
// then descend to the target location, creating as we go, if need be
if pathString != "" {
path := strings.Split(pathString, "/")
// find (or create) the location we want to put this value at
for _, dir := range path {
if _, ok := target[dir]; !ok {
target[dir] = make(map[string]interface{})
}
target = target[dir].(map[string]interface{})
path := strings.Split(pathString, "/")
// find (or create) the leaf node we want to put this value at
for _, dir := range path[:len(path)-1] {
if _, ok := target[dir]; !ok {
target[dir] = make(map[string]interface{})
}
target = target[dir].(map[string]interface{})
}
leafDir := path[len(path)-1]
// copy over the keys from the value
for k := range val {
target[k] = val[k]
switch val.(type) {
case *configArrayValue:
target[leafDir] = val.Value()
case *configMapValue:
target[leafDir] = make(map[string]interface{})
target = target[leafDir].(map[string]interface{})
mapv := val.Value().(map[string]interface{})
for k := range mapv {
target[k] = mapv[k]
}
}
}

View File

@@ -1,51 +0,0 @@
# Etcd Source
The etcd source reads config from etcd key/values
This source supports etcd version 3 and beyond.
## Etcd Format
The etcd source expects keys under the default prefix `/micro/config` (prefix can be changed)
Values are expected to be JSON
```
// set database
etcdctl put /micro/config/database '{"address": "10.0.0.1", "port": 3306}'
// set cache
etcdctl put /micro/config/cache '{"address": "10.0.0.2", "port": 6379}'
```
Keys are split on `/` so access becomes
```
conf.Get("micro", "config", "database")
```
## New Source
Specify source with data
```go
etcdSource := etcd.NewSource(
// optionally specify etcd address; default to localhost:8500
etcd.WithAddress("10.0.0.10:8500"),
// optionally specify prefix; defaults to /micro/config
etcd.WithPrefix("/my/prefix"),
// optionally strip the provided prefix from the keys, defaults to false
etcd.StripPrefix(true),
)
```
## Load Source
Load the source into config
```go
// Create new config
conf := config.NewConfig()
// Load file source
conf.Load(etcdSource)
```

View File

@@ -1,134 +0,0 @@
package etcd
import (
"context"
"fmt"
"net"
"time"
"github.com/micro/go-micro/config/source"
cetcd "go.etcd.io/etcd/clientv3"
"go.etcd.io/etcd/mvcc/mvccpb"
)
// Currently a single etcd reader
type etcd struct {
prefix string
stripPrefix string
opts source.Options
client *cetcd.Client
cerr error
}
var (
DefaultPrefix = "/micro/config/"
)
func (c *etcd) Read() (*source.ChangeSet, error) {
if c.cerr != nil {
return nil, c.cerr
}
rsp, err := c.client.Get(context.Background(), c.prefix, cetcd.WithPrefix())
if err != nil {
return nil, err
}
if rsp == nil || len(rsp.Kvs) == 0 {
return nil, fmt.Errorf("source not found: %s", c.prefix)
}
var kvs []*mvccpb.KeyValue
for _, v := range rsp.Kvs {
kvs = append(kvs, (*mvccpb.KeyValue)(v))
}
data := makeMap(c.opts.Encoder, kvs, c.stripPrefix)
b, err := c.opts.Encoder.Encode(data)
if err != nil {
return nil, fmt.Errorf("error reading source: %v", err)
}
cs := &source.ChangeSet{
Timestamp: time.Now(),
Source: c.String(),
Data: b,
Format: c.opts.Encoder.String(),
}
cs.Checksum = cs.Sum()
return cs, nil
}
func (c *etcd) String() string {
return "etcd"
}
func (c *etcd) Watch() (source.Watcher, error) {
if c.cerr != nil {
return nil, c.cerr
}
cs, err := c.Read()
if err != nil {
return nil, err
}
return newWatcher(c.prefix, c.stripPrefix, c.client.Watcher, cs, c.opts)
}
func NewSource(opts ...source.Option) source.Source {
options := source.NewOptions(opts...)
var endpoints []string
// check if there are any addrs
addrs, ok := options.Context.Value(addressKey{}).([]string)
if ok {
for _, a := range addrs {
addr, port, err := net.SplitHostPort(a)
if ae, ok := err.(*net.AddrError); ok && ae.Err == "missing port in address" {
port = "2379"
addr = a
endpoints = append(endpoints, fmt.Sprintf("%s:%s", addr, port))
} else if err == nil {
endpoints = append(endpoints, fmt.Sprintf("%s:%s", addr, port))
}
}
}
if len(endpoints) == 0 {
endpoints = []string{"localhost:2379"}
}
config := cetcd.Config{
Endpoints: endpoints,
}
u, ok := options.Context.Value(authKey{}).(*authCreds)
if ok {
config.Username = u.Username
config.Password = u.Password
}
// use default config
client, err := cetcd.New(config)
prefix := DefaultPrefix
sp := ""
f, ok := options.Context.Value(prefixKey{}).(string)
if ok {
prefix = f
}
if b, ok := options.Context.Value(stripPrefixKey{}).(bool); ok && b {
sp = prefix
}
return &etcd{
prefix: prefix,
stripPrefix: sp,
opts: options,
client: client,
cerr: err,
}
}

View File

@@ -1,58 +0,0 @@
package etcd
import (
"context"
"github.com/micro/go-micro/config/source"
)
type addressKey struct{}
type prefixKey struct{}
type stripPrefixKey struct{}
type authKey struct{}
type authCreds struct {
Username string
Password string
}
// WithAddress sets the consul address
func WithAddress(a ...string) source.Option {
return func(o *source.Options) {
if o.Context == nil {
o.Context = context.Background()
}
o.Context = context.WithValue(o.Context, addressKey{}, a)
}
}
// WithPrefix sets the key prefix to use
func WithPrefix(p string) source.Option {
return func(o *source.Options) {
if o.Context == nil {
o.Context = context.Background()
}
o.Context = context.WithValue(o.Context, prefixKey{}, p)
}
}
// StripPrefix indicates whether to remove the prefix from config entries, or leave it in place.
func StripPrefix(strip bool) source.Option {
return func(o *source.Options) {
if o.Context == nil {
o.Context = context.Background()
}
o.Context = context.WithValue(o.Context, stripPrefixKey{}, strip)
}
}
// Auth allows you to specify username/password
func Auth(username, password string) source.Option {
return func(o *source.Options) {
if o.Context == nil {
o.Context = context.Background()
}
o.Context = context.WithValue(o.Context, authKey{}, &authCreds{Username: username, Password: password})
}
}

View File

@@ -1,89 +0,0 @@
package etcd
import (
"strings"
"github.com/micro/go-micro/config/encoder"
"go.etcd.io/etcd/clientv3"
"go.etcd.io/etcd/mvcc/mvccpb"
)
func makeEvMap(e encoder.Encoder, data map[string]interface{}, kv []*clientv3.Event, stripPrefix string) map[string]interface{} {
if data == nil {
data = make(map[string]interface{})
}
for _, v := range kv {
switch mvccpb.Event_EventType(v.Type) {
case mvccpb.DELETE:
data = update(e, data, (*mvccpb.KeyValue)(v.Kv), "delete", stripPrefix)
default:
data = update(e, data, (*mvccpb.KeyValue)(v.Kv), "insert", stripPrefix)
}
}
return data
}
func makeMap(e encoder.Encoder, kv []*mvccpb.KeyValue, stripPrefix string) map[string]interface{} {
data := make(map[string]interface{})
for _, v := range kv {
data = update(e, data, v, "put", stripPrefix)
}
return data
}
func update(e encoder.Encoder, data map[string]interface{}, v *mvccpb.KeyValue, action, stripPrefix string) map[string]interface{} {
// remove prefix if non empty, and ensure leading / is removed as well
vkey := strings.TrimPrefix(strings.TrimPrefix(string(v.Key), stripPrefix), "/")
// split on prefix
haveSplit := strings.Contains(vkey, "/")
keys := strings.Split(vkey, "/")
var vals interface{}
e.Decode(v.Value, &vals)
if !haveSplit && len(keys) == 1 {
switch action {
case "delete":
data = make(map[string]interface{})
default:
v, ok := vals.(map[string]interface{})
if ok {
data = v
}
}
return data
}
// set data for first iteration
kvals := data
// iterate the keys and make maps
for i, k := range keys {
kval, ok := kvals[k].(map[string]interface{})
if !ok {
// create next map
kval = make(map[string]interface{})
// set it
kvals[k] = kval
}
// last key: write vals
if l := len(keys) - 1; i == l {
switch action {
case "delete":
delete(kvals, k)
default:
kvals[k] = vals
}
break
}
// set kvals for next iterator
kvals = kval
}
return data
}

View File

@@ -1,113 +0,0 @@
package etcd
import (
"context"
"errors"
"sync"
"time"
"github.com/micro/go-micro/config/source"
cetcd "go.etcd.io/etcd/clientv3"
)
type watcher struct {
opts source.Options
name string
stripPrefix string
sync.RWMutex
cs *source.ChangeSet
ch chan *source.ChangeSet
exit chan bool
}
func newWatcher(key, strip string, wc cetcd.Watcher, cs *source.ChangeSet, opts source.Options) (source.Watcher, error) {
w := &watcher{
opts: opts,
name: "etcd",
stripPrefix: strip,
cs: cs,
ch: make(chan *source.ChangeSet),
exit: make(chan bool),
}
ch := wc.Watch(context.Background(), key, cetcd.WithPrefix())
go w.run(wc, ch)
return w, nil
}
func (w *watcher) handle(evs []*cetcd.Event) {
w.RLock()
data := w.cs.Data
w.RUnlock()
var vals map[string]interface{}
// unpackage existing changeset
if err := w.opts.Encoder.Decode(data, &vals); err != nil {
return
}
// update base changeset
d := makeEvMap(w.opts.Encoder, vals, evs, w.stripPrefix)
// pack the changeset
b, err := w.opts.Encoder.Encode(d)
if err != nil {
return
}
// create new changeset
cs := &source.ChangeSet{
Timestamp: time.Now(),
Source: w.name,
Data: b,
Format: w.opts.Encoder.String(),
}
cs.Checksum = cs.Sum()
// set base change set
w.Lock()
w.cs = cs
w.Unlock()
// send update
w.ch <- cs
}
func (w *watcher) run(wc cetcd.Watcher, ch cetcd.WatchChan) {
for {
select {
case rsp, ok := <-ch:
if !ok {
return
}
w.handle(rsp.Events)
case <-w.exit:
wc.Close()
return
}
}
}
func (w *watcher) Next() (*source.ChangeSet, error) {
select {
case cs := <-w.ch:
return cs, nil
case <-w.exit:
return nil, errors.New("watcher stopped")
}
}
func (w *watcher) Stop() error {
select {
case <-w.exit:
return nil
default:
close(w.exit)
}
return nil
}

View File

@@ -5,8 +5,8 @@ import (
"sync"
"time"
"github.com/google/uuid"
"github.com/micro/go-micro/config/source"
"github.com/pborman/uuid"
)
type memory struct {
@@ -29,7 +29,7 @@ func (s *memory) Read() (*source.ChangeSet, error) {
func (s *memory) Watch() (source.Watcher, error) {
w := &watcher{
Id: uuid.NewUUID().String(),
Id: uuid.New().String(),
Updates: make(chan *source.ChangeSet, 100),
Source: s,
}

2
data/data.go Normal file
View File

@@ -0,0 +1,2 @@
// Package data is an interface for data access
package data

View File

@@ -6,24 +6,26 @@ import (
"net"
"github.com/hashicorp/consul/api"
"github.com/micro/go-micro/sync/data"
"github.com/micro/go-micro/config/options"
"github.com/micro/go-micro/data/store"
)
type ckv struct {
options.Options
client *api.Client
}
func (c *ckv) Read(key string) (*data.Record, error) {
func (c *ckv) Read(key string) (*store.Record, error) {
keyval, _, err := c.client.KV().Get(key, nil)
if err != nil {
return nil, err
}
if keyval == nil {
return nil, data.ErrNotFound
return nil, store.ErrNotFound
}
return &data.Record{
return &store.Record{
Key: keyval.Key,
Value: keyval.Value,
}, nil
@@ -34,7 +36,7 @@ func (c *ckv) Delete(key string) error {
return err
}
func (c *ckv) Write(record *data.Record) error {
func (c *ckv) Write(record *store.Record) error {
_, err := c.client.KV().Put(&api.KVPair{
Key: record.Key,
Value: record.Value,
@@ -42,17 +44,17 @@ func (c *ckv) Write(record *data.Record) error {
return err
}
func (c *ckv) Dump() ([]*data.Record, error) {
func (c *ckv) Dump() ([]*store.Record, error) {
keyval, _, err := c.client.KV().List("/", nil)
if err != nil {
return nil, err
}
if keyval == nil {
return nil, data.ErrNotFound
return nil, store.ErrNotFound
}
var vals []*data.Record
var vals []*store.Record
for _, keyv := range keyval {
vals = append(vals, &data.Record{
vals = append(vals, &store.Record{
Key: keyv.Key,
Value: keyv.Value,
})
@@ -64,22 +66,22 @@ func (c *ckv) String() string {
return "consul"
}
func NewData(opts ...data.Option) data.Data {
var options data.Options
for _, o := range opts {
o(&options)
}
func NewStore(opts ...options.Option) store.Store {
options := options.NewOptions(opts...)
config := api.DefaultConfig()
var nodes []string
if n, ok := options.Values().Get("store.nodes"); ok {
nodes = n.([]string)
}
// set host
// config.Host something
// check if there are any addrs
if len(options.Nodes) > 0 {
addr, port, err := net.SplitHostPort(options.Nodes[0])
if len(nodes) > 0 {
addr, port, err := net.SplitHostPort(nodes[0])
if ae, ok := err.(*net.AddrError); ok && ae.Err == "missing port in address" {
port = "8500"
config.Address = fmt.Sprintf("%s:%s", options.Nodes[0], port)
config.Address = fmt.Sprintf("%s:%s", nodes[0], port)
} else if err == nil {
config.Address = fmt.Sprintf("%s:%s", addr, port)
}
@@ -88,6 +90,7 @@ func NewData(opts ...data.Option) data.Data {
client, _ := api.NewClient(config)
return &ckv{
client: client,
Options: options,
client: client,
}
}

108
data/store/memory/memory.go Normal file
View File

@@ -0,0 +1,108 @@
// Package memory is a in-memory store store
package memory
import (
"sync"
"time"
"github.com/micro/go-micro/config/options"
"github.com/micro/go-micro/data/store"
)
type memoryStore struct {
options.Options
sync.RWMutex
values map[string]*memoryRecord
}
type memoryRecord struct {
r *store.Record
c time.Time
}
func (m *memoryStore) Dump() ([]*store.Record, error) {
m.RLock()
defer m.RUnlock()
var values []*store.Record
for _, v := range m.values {
// get expiry
d := v.r.Expiry
t := time.Since(v.c)
if d > time.Duration(0) {
// expired
if t > d {
continue
}
// update expiry
v.r.Expiry -= t
v.c = time.Now()
}
values = append(values, v.r)
}
return values, nil
}
func (m *memoryStore) Read(key string) (*store.Record, error) {
m.RLock()
defer m.RUnlock()
v, ok := m.values[key]
if !ok {
return nil, store.ErrNotFound
}
// get expiry
d := v.r.Expiry
t := time.Since(v.c)
// expired
if d > time.Duration(0) {
if t > d {
return nil, store.ErrNotFound
}
// update expiry
v.r.Expiry -= t
v.c = time.Now()
}
return v.r, nil
}
func (m *memoryStore) Write(r *store.Record) error {
m.Lock()
defer m.Unlock()
// set the record
m.values[r.Key] = &memoryRecord{
r: r,
c: time.Now(),
}
return nil
}
func (m *memoryStore) Delete(key string) error {
m.Lock()
defer m.Unlock()
// delete the value
delete(m.values, key)
return nil
}
// NewStore returns a new store.Store
func NewStore(opts ...options.Option) store.Store {
options := options.NewOptions(opts...)
return &memoryStore{
Options: options,
values: make(map[string]*memoryRecord),
}
}

View File

@@ -0,0 +1,37 @@
package memory
import (
"testing"
"time"
"github.com/micro/go-micro/data/store"
)
func TestReadRecordExpire(t *testing.T) {
s := NewStore()
var (
key = "foo"
expire = 100 * time.Millisecond
)
rec := &store.Record{
Key: key,
Value: nil,
Expiry: expire,
}
s.Write(rec)
rrec, err := s.Read(key)
if err != nil {
t.Fatal(err)
}
if rrec.Expiry >= expire {
t.Fatal("expiry of read record is not changed")
}
time.Sleep(expire)
if _, err := s.Read(key); err != store.ErrNotFound {
t.Fatal("expire elapsed, but key still accessable")
}
}

15
data/store/options.go Normal file
View File

@@ -0,0 +1,15 @@
package store
import (
"github.com/micro/go-micro/config/options"
)
// Set the nodes used to back the store
func Nodes(a ...string) options.Option {
return options.WithValue("store.nodes", a)
}
// Prefix sets a prefix to any key ids used
func Prefix(p string) options.Option {
return options.WithValue("store.prefix", p)
}

View File

@@ -1,17 +1,21 @@
// Package data is an interface for key-value storage.
package data
// Package store is an interface for distribute data storage.
package store
import (
"errors"
"time"
"github.com/micro/go-micro/config/options"
)
var (
ErrNotFound = errors.New("not found")
)
// Data is a data storage interface
type Data interface {
// Store is a data storage interface
type Store interface {
// embed options
options.Options
// Dump the known records
Dump() ([]*Record, error)
// Read a record with key
@@ -24,9 +28,7 @@ type Data interface {
// Record represents a data record
type Record struct {
Key string
Value []byte
Expiration time.Duration
Key string
Value []byte
Expiry time.Duration
}
type Option func(o *Options)

View File

@@ -14,7 +14,7 @@ func TestFunction(t *testing.T) {
wg.Add(1)
r := memory.NewRegistry()
r.(*memory.Registry).Setup()
r.(*memory.Registry).Services = testData
// create service
fn := NewFunction(

98
go.mod
View File

@@ -1,58 +1,36 @@
module github.com/micro/go-micro
exclude (
github.com/Sirupsen/logrus v1.1.0
github.com/Sirupsen/logrus v1.1.1
github.com/Sirupsen/logrus v1.2.0
github.com/Sirupsen/logrus v1.3.0
github.com/Sirupsen/logrus v1.4.0
github.com/Sirupsen/logrus v1.4.1
github.com/Sirupsen/logrus v1.4.2
sourcegraph.com/sourcegraph/go-diff v0.5.1
)
replace (
github.com/golang/lint => github.com/golang/lint v0.0.0-20190227174305-8f45f776aaf1
github.com/nats-io/go-nats => github.com/nats-io/nats.go v1.8.1
github.com/nats-io/go-nats-streaming => github.com/nats-io/stan.go v0.5.0
github.com/testcontainers/testcontainer-go => github.com/testcontainers/testcontainers-go v0.0.0-20181115231424-8e868ca12c0f
)
go 1.12
require (
cloud.google.com/go v0.39.0 // indirect
cloud.google.com/go v0.41.0 // indirect
github.com/BurntSushi/toml v0.3.1
github.com/OneOfOne/xxhash v1.2.5 // indirect
github.com/armon/circbuf v0.0.0-20190214190532-5111143e8da2 // indirect
github.com/armon/go-metrics v0.0.0-20190430140413-ec5e00d3c878 // indirect
github.com/armon/go-radix v1.0.0 // indirect
github.com/beevik/ntp v0.2.0
github.com/bitly/go-simplejson v0.5.0
github.com/bradfitz/gomemcache v0.0.0-20190329173943-551aad21a668
github.com/bwmarrin/discordgo v0.19.0
github.com/containerd/continuity v0.0.0-20190426062206-aaeac12a7ffc // indirect
github.com/coreos/etcd v3.3.13+incompatible
github.com/dgryski/go-sip13 v0.0.0-20190329191031-25c5027a8c7b // indirect
github.com/emirpasic/gods v1.12.0 // indirect
github.com/forestgiant/sliceutil v0.0.0-20160425183142-94783f95db6c
github.com/fsnotify/fsnotify v1.4.7
github.com/fsouza/go-dockerclient v1.4.1
github.com/ghodss/yaml v1.0.0
github.com/gliderlabs/ssh v0.1.4 // indirect
github.com/gliderlabs/ssh v0.2.2 // indirect
github.com/go-kit/kit v0.9.0 // indirect
github.com/go-log/log v0.1.0
github.com/go-playground/locales v0.12.1 // indirect
github.com/go-playground/universal-translator v0.16.0 // indirect
github.com/go-redsync/redsync v1.2.0
github.com/golang/mock v1.3.1 // indirect
github.com/golang/protobuf v1.3.1
github.com/gomodule/redigo v2.0.0+incompatible
github.com/google/btree v1.0.0 // indirect
github.com/google/pprof v0.0.0-20190515194954-54271f7e092f // indirect
github.com/golang/protobuf v1.3.2
github.com/google/uuid v1.1.1
github.com/gorilla/handlers v1.4.0
github.com/gorilla/handlers v1.4.1
github.com/gorilla/mux v1.7.3 // indirect
github.com/gorilla/websocket v1.4.0
github.com/hashicorp/consul/api v1.1.0
github.com/hashicorp/go-immutable-radix v1.1.0 // indirect
github.com/hashicorp/go-msgpack v0.5.5 // indirect
github.com/hashicorp/go-retryablehttp v0.5.4 // indirect
github.com/hashicorp/go-rootcerts v1.0.1 // indirect
github.com/hashicorp/go-sockaddr v1.0.2 // indirect
github.com/hashicorp/go-version v1.2.0 // indirect
github.com/hashicorp/hcl v1.0.0
@@ -62,59 +40,45 @@ require (
github.com/imdario/mergo v0.3.7
github.com/joncalhoun/qson v0.0.0-20170526102502-8a9cab3a62b1
github.com/json-iterator/go v1.1.6
github.com/kevinburke/ssh_config v0.0.0-20190630040420-2e50c441276c // indirect
github.com/kisielk/errcheck v1.2.0 // indirect
github.com/konsorten/go-windows-terminal-sequences v1.0.2 // indirect
github.com/kr/pty v1.1.4 // indirect
github.com/kr/pty v1.1.8 // indirect
github.com/leodido/go-urn v1.1.0 // indirect
github.com/lucas-clemente/quic-go v0.11.2
github.com/marten-seemann/qtls v0.2.4 // indirect
github.com/lucas-clemente/quic-go v0.7.1-0.20190710050138-1441923ab031
github.com/mattn/go-colorable v0.1.2 // indirect
github.com/mattn/go-runewidth v0.0.4 // indirect
github.com/micro/cli v0.2.0
github.com/micro/mdns v0.1.0
github.com/miekg/dns v1.1.13 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/micro/mdns v0.2.0
github.com/miekg/dns v1.1.15 // indirect
github.com/mitchellh/gox v1.0.1 // indirect
github.com/mitchellh/hashstructure v1.0.0
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.1 // indirect
github.com/nats-io/nats.go v1.8.1
github.com/nats-io/nkeys v0.1.0 // indirect
github.com/nlopes/slack v0.5.0
github.com/olekukonko/tablewriter v0.0.1
github.com/onsi/ginkgo v1.8.0 // indirect
github.com/onsi/gomega v1.5.0 // indirect
github.com/pborman/uuid v1.2.0
github.com/pkg/errors v0.8.1
github.com/posener/complete v1.2.1 // indirect
github.com/prometheus/client_golang v0.9.3 // indirect
github.com/prometheus/common v0.4.1 // indirect
github.com/prometheus/procfs v0.0.2 // indirect
github.com/prometheus/tsdb v0.8.0 // indirect
github.com/prometheus/common v0.6.0 // indirect
github.com/prometheus/procfs v0.0.3 // indirect
github.com/sirupsen/logrus v1.4.2 // indirect
github.com/spaolacci/murmur3 v1.1.0 // indirect
github.com/stretchr/objx v0.2.0 // indirect
github.com/technoweenie/multipartstreamer v1.0.1 // indirect
github.com/xanzy/ssh-agent v0.2.1 // indirect
go.etcd.io/etcd v3.3.13+incompatible
go.opencensus.io v0.22.0 // indirect
golang.org/x/crypto v0.0.0-20190530122614-20be4c3c3ed5
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522 // indirect
golang.org/x/image v0.0.0-20190523035834-f03afa92d3ff // indirect
golang.org/x/lint v0.0.0-20190409202823-959b441ac422 // indirect
golang.org/x/mobile v0.0.0-20190509164839-32b2708ab171 // indirect
golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4
golang.org/x/exp v0.0.0-20190627132806-fd42eb6b336f // indirect
golang.org/x/image v0.0.0-20190703141733-d6a02ce849c9 // indirect
golang.org/x/mobile v0.0.0-20190711165009-e47acb2ca7f9 // indirect
golang.org/x/mod v0.1.0 // indirect
golang.org/x/net v0.0.0-20190603091049-60506f45cf65
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45 // indirect
golang.org/x/sys v0.0.0-20190602015325-4c4f7f33c9ed // indirect
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4 // indirect
golang.org/x/tools v0.0.0-20190603231351-8aaa1484dc10 // indirect
google.golang.org/appengine v1.6.0 // indirect
google.golang.org/genproto v0.0.0-20190530194941-fb225487d101 // indirect
google.golang.org/grpc v1.21.1
gopkg.in/bsm/ratelimit.v1 v1.0.0-20160220154919-db14e161995a // indirect
golang.org/x/net v0.0.0-20190628185345-da137c7871d7
golang.org/x/sys v0.0.0-20190710143415-6ec70d6a5542 // indirect
golang.org/x/tools v0.0.0-20190711191110-9a621aea19f8 // indirect
google.golang.org/genproto v0.0.0-20190708153700-3bdd9d9f5532 // indirect
google.golang.org/grpc v1.22.0
gopkg.in/go-playground/validator.v9 v9.29.0
gopkg.in/redis.v3 v3.6.4
gopkg.in/src-d/go-billy.v4 v4.3.0 // indirect
gopkg.in/src-d/go-git-fixtures.v3 v3.5.0 // indirect
gopkg.in/src-d/go-git.v4 v4.11.0
gopkg.in/src-d/go-billy.v4 v4.3.1 // indirect
gopkg.in/src-d/go-git.v4 v4.12.0
gopkg.in/telegram-bot-api.v4 v4.6.4
honnef.co/go/tools v0.0.0-20190604153307-63e9ff576adb // indirect
honnef.co/go/tools v0.0.0-20190614002413-cb51c254f01b // indirect
)

1833
go.sum

File diff suppressed because it is too large Load Diff

BIN
micro.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

288
network/link/default.go Normal file
View File

@@ -0,0 +1,288 @@
// Package link provides a measured transport.Socket link
package link
import (
"io"
"sync"
"time"
"github.com/micro/go-micro/config/options"
"github.com/micro/go-micro/transport"
)
type link struct {
sync.RWMutex
// the link id
id string
// the remote end to dial
addr string
// channel used to close the link
closed chan bool
// if its connected
connected bool
// the transport to use
transport transport.Transport
// the send queue to the socket
sendQueue chan *transport.Message
// the recv queue to the socket
recvQueue chan *transport.Message
// the socket for this link
socket transport.Socket
// determines the cost of the link
// based on queue length and roundtrip
length int
weight int
}
func newLink(options options.Options) *link {
// default values
var sock transport.Socket
var addr string
id := "local"
tr := transport.DefaultTransport
lid, ok := options.Values().Get("link.id")
if ok {
id = lid.(string)
}
laddr, ok := options.Values().Get("link.address")
if ok {
addr = laddr.(string)
}
ltr, ok := options.Values().Get("link.transport")
if ok {
tr = ltr.(transport.Transport)
}
lsock, ok := options.Values().Get("link.socket")
if ok {
sock = lsock.(transport.Socket)
}
l := &link{
// the remote end to dial
addr: addr,
// transport to dial link
transport: tr,
// the socket to use
// this is nil if not specified
socket: sock,
// unique id assigned to the link
id: id,
// the closed channel used to close the conn
closed: make(chan bool),
// then send queue
sendQueue: make(chan *transport.Message, 128),
// the receive queue
recvQueue: make(chan *transport.Message, 128),
}
// return the link
return l
}
// link methods
// process processes messages on the send and receive queues.
func (l *link) process() {
go func() {
for {
m := new(transport.Message)
if err := l.recv(m); err != nil {
return
}
select {
case l.recvQueue <- m:
case <-l.closed:
return
}
}
}()
// messages sent
i := 0
length := 0
for {
select {
case m := <-l.sendQueue:
t := time.Now()
// send the message
if err := l.send(m); err != nil {
return
}
// get header size, body size and time taken
hl := len(m.Header)
bl := len(m.Body)
d := time.Since(t)
// don't calculate on empty messages
if hl == 0 && bl == 0 {
continue
}
// increment sent
i++
// time take to send some bits and bytes
td := float64(hl+bl) / float64(d.Nanoseconds())
// increase the scale
td += 1
// judge the length
length = int(td) / (length + int(td))
// every 10 messages update length
if (i % 10) == 1 {
// cost average the length
// save it
l.Lock()
l.length = length
l.Unlock()
}
case <-l.closed:
return
}
}
}
// send a message over the link
func (l *link) send(m *transport.Message) error {
// TODO: measure time taken and calculate length/rate
// send via the transport socket
return l.socket.Send(m)
}
// recv a message on the link
func (l *link) recv(m *transport.Message) error {
if m.Header == nil {
m.Header = make(map[string]string)
}
// receive the transport message
return l.socket.Recv(m)
}
// Connect attempts to connect to an address and sets the socket
func (l *link) Connect() error {
l.Lock()
if l.connected {
l.Unlock()
return nil
}
defer l.Unlock()
// replace closed
l.closed = make(chan bool)
// assume existing socket
if len(l.addr) == 0 {
go l.process()
return nil
}
// dial the endpoint
c, err := l.transport.Dial(l.addr)
if err != nil {
return err
}
// set the socket
l.socket = c
// kick start the processing
go l.process()
return nil
}
// Close the link
func (l *link) Close() error {
select {
case <-l.closed:
return nil
default:
close(l.closed)
l.Lock()
l.connected = false
l.Unlock()
return l.socket.Close()
}
}
// returns the node id
func (l *link) Id() string {
l.RLock()
defer l.RUnlock()
return l.id
}
// the remote ip of the link
func (l *link) Remote() string {
l.RLock()
defer l.RUnlock()
return l.socket.Remote()
}
// the local ip of the link
func (l *link) Local() string {
l.RLock()
defer l.RUnlock()
return l.socket.Local()
}
// length/rate of the link
func (l *link) Length() int {
l.RLock()
defer l.RUnlock()
return l.length
}
// weight checks the size of the queues
func (l *link) Weight() int {
return len(l.sendQueue) + len(l.recvQueue)
}
// Accept accepts a message on the socket
func (l *link) Recv(m *transport.Message) error {
select {
case <-l.closed:
return io.EOF
case rm := <-l.recvQueue:
*m = *rm
return nil
}
// never reach
return nil
}
// Send sends a message on the socket immediately
func (l *link) Send(m *transport.Message) error {
select {
case <-l.closed:
return io.EOF
case l.sendQueue <- m:
}
return nil
}
func (l *link) Status() string {
select {
case <-l.closed:
return "closed"
default:
return "connected"
}
}

60
network/link/link.go Normal file
View File

@@ -0,0 +1,60 @@
// Package link provides a measured link on top of a transport.Socket
package link
import (
"errors"
"github.com/micro/go-micro/config/options"
"github.com/micro/go-micro/transport"
)
// Link is a layer on top of a transport socket with the
// buffering send and recv queue's with the ability to
// measure the actual transport link and reconnect if
// an address is specified.
type Link interface {
// provides the transport.Socket interface
transport.Socket
// Connect connects the link. It must be called first
// if there's an expectation to create a new socket.
Connect() error
// Id of the link is "local" if not specified
Id() string
// Status of the link
Status() string
// Depth of the buffers
Weight() int
// Rate of the link
Length() int
}
var (
ErrLinkClosed = errors.New("link closed")
)
// NewLink creates a new link on top of a socket
func NewLink(opts ...options.Option) Link {
return newLink(options.NewOptions(opts...))
}
// Sets the link id which otherwise defaults to "local"
func Id(id string) options.Option {
return options.WithValue("link.id", id)
}
// The address to use for the link. Connect must be
// called for this to be used, its otherwise unused.
func Address(a string) options.Option {
return options.WithValue("link.address", a)
}
// The transport to use for the link where we
// want to dial the connection first.
func Transport(t transport.Transport) options.Option {
return options.WithValue("link.transport", t)
}
// Socket sets the socket to use instead of dialing.
func Socket(s transport.Socket) options.Option {
return options.WithValue("link.socket", s)
}

158
network/proxy/grpc/grpc.go Normal file
View File

@@ -0,0 +1,158 @@
// Package grpc transparently forwards the grpc protocol using a go-micro client.
package grpc
import (
"context"
"io"
"strings"
"github.com/micro/go-micro/client"
"github.com/micro/go-micro/client/grpc"
"github.com/micro/go-micro/codec"
"github.com/micro/go-micro/config/options"
"github.com/micro/go-micro/network/proxy"
"github.com/micro/go-micro/server"
)
// Proxy will transparently proxy requests to the backend.
// If no backend is specified it will call a service using the client.
// If the service matches the Name it will use the server.DefaultRouter.
type Proxy struct {
// The proxy options
options.Options
// Endpoint specified the fixed endpoint to call.
Endpoint string
// The client to use for outbound requests
Client client.Client
}
// read client request and write to server
func readLoop(r server.Request, s client.Stream) error {
// request to backend server
req := s.Request()
for {
// get data from client
// no need to decode it
body, err := r.Read()
if err == io.EOF {
return nil
}
if err != nil {
return err
}
// get the header from client
hdr := r.Header()
msg := &codec.Message{
Type: codec.Request,
Header: hdr,
Body: body,
}
// write the raw request
err = req.Codec().Write(msg, nil)
if err == io.EOF {
return nil
} else if err != nil {
return err
}
}
}
// ServeRequest honours the server.Proxy interface
func (p *Proxy) ServeRequest(ctx context.Context, req server.Request, rsp server.Response) error {
// set default client
if p.Client == nil {
p.Client = grpc.NewClient()
}
opts := []client.CallOption{}
// service name
service := req.Service()
endpoint := req.Endpoint()
// call a specific backend
if len(p.Endpoint) > 0 {
// address:port
if parts := strings.Split(p.Endpoint, ":"); len(parts) > 1 {
opts = append(opts, client.WithAddress(p.Endpoint))
// use as service name
} else {
service = p.Endpoint
}
}
// create new request with raw bytes body
creq := p.Client.NewRequest(service, endpoint, nil, client.WithContentType(req.ContentType()))
// create new stream
stream, err := p.Client.Stream(ctx, creq, opts...)
if err != nil {
return err
}
defer stream.Close()
// create client request read loop
go readLoop(req, stream)
// get raw response
resp := stream.Response()
// create server response write loop
for {
// read backend response body
body, err := resp.Read()
if err == io.EOF {
return nil
} else if err != nil {
return err
}
// read backend response header
hdr := resp.Header()
// write raw response header to client
rsp.WriteHeader(hdr)
// write raw response body to client
err = rsp.Write(body)
if err == io.EOF {
return nil
} else if err != nil {
return err
}
}
return nil
}
// NewProxy returns a new grpc proxy server
func NewProxy(opts ...options.Option) proxy.Proxy {
p := new(Proxy)
p.Options = options.NewOptions(opts...)
p.Options.Init(options.WithString("grpc"))
// get endpoint
ep, ok := p.Options.Values().Get("proxy.endpoint")
if ok {
p.Endpoint = ep.(string)
}
// get client
c, ok := p.Options.Values().Get("proxy.client")
if ok {
p.Client = c.(client.Client)
}
return p
}
// NewSingleHostProxy returns a router which sends requests to a single backend
func NewSingleHostProxy(url string) *Proxy {
return &Proxy{
Endpoint: url,
}
}

View File

@@ -10,27 +10,23 @@ import (
"net/url"
"path"
"github.com/micro/go-micro"
"github.com/micro/go-micro/config/options"
"github.com/micro/go-micro/errors"
"github.com/micro/go-micro/network/proxy"
"github.com/micro/go-micro/server"
)
// Router will proxy rpc requests as http POST requests. It is a server.Router
type Router struct {
// Proxy will proxy rpc requests as http POST requests. It is a server.Proxy
type Proxy struct {
options.Options
// The http backend to call
Backend string
Endpoint string
// first request
first bool
}
var (
// The default backend
DefaultBackend = "http://localhost:9090"
// The default router
DefaultRouter = &Router{}
)
func getMethod(hdr map[string]string) string {
switch hdr["Micro-Method"] {
case "GET", "HEAD", "POST", "PUT", "DELETE", "CONNECT", "OPTIONS", "TRACE", "PATCH":
@@ -49,9 +45,9 @@ func getEndpoint(hdr map[string]string) string {
}
// ServeRequest honours the server.Router interface
func (p *Router) ServeRequest(ctx context.Context, req server.Request, rsp server.Response) error {
if p.Backend == "" {
p.Backend = DefaultBackend
func (p *Proxy) ServeRequest(ctx context.Context, req server.Request, rsp server.Response) error {
if p.Endpoint == "" {
p.Endpoint = proxy.DefaultEndpoint
}
for {
@@ -75,10 +71,10 @@ func (p *Router) ServeRequest(ctx context.Context, req server.Request, rsp serve
// set the endpoint
if len(endpoint) == 0 {
endpoint = p.Backend
endpoint = p.Endpoint
} else {
// add endpoint to backend
u, err := url.Parse(p.Backend)
u, err := url.Parse(p.Endpoint)
if err != nil {
return errors.InternalServerError(req.Service(), err.Error())
}
@@ -130,48 +126,24 @@ func (p *Router) ServeRequest(ctx context.Context, req server.Request, rsp serve
return nil
}
// NewSingleHostRouter returns a router which sends requests to a single http backend
//
// It is used by setting it in a new micro service to act as a proxy for a http backend.
//
// Usage:
//
// Create a new router to the http backend
//
// r := NewSingleHostRouter("http://localhost:10001")
//
// // Create your new service
// service := micro.NewService(
// micro.Name("greeter"),
// // Set the router
// http.WithRouter(r),
// )
//
// // Run the service
// service.Run()
func NewSingleHostRouter(url string) *Router {
return &Router{
Backend: url,
// NewSingleHostProxy returns a router which sends requests to a single http backend
func NewSingleHostProxy(url string) proxy.Proxy {
return &Proxy{
Endpoint: url,
}
}
// NewService returns a new http proxy. It acts as a micro service proxy.
// Any request on the transport is routed to a fixed http backend.
//
// Usage:
//
// service := NewService(
// micro.Name("greeter"),
// // Sets the default http endpoint
// http.WithBackend("http://localhost:10001"),
// )
//
func NewService(opts ...micro.Option) micro.Service {
// prepend router to opts
opts = append([]micro.Option{
WithRouter(DefaultRouter),
}, opts...)
// NewProxy returns a new proxy which will route using a http client
func NewProxy(opts ...options.Option) proxy.Proxy {
p := new(Proxy)
p.Options = options.NewOptions(opts...)
p.Options.Init(options.WithString("http"))
// create the new service
return micro.NewService(opts...)
// get endpoint
ep, ok := p.Options.Values().Get("proxy.endpoint")
if ok {
p.Endpoint = ep.(string)
}
return p
}

View File

@@ -20,7 +20,7 @@ func (t *testHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"hello": "world"}`))
}
func TestHTTPRouter(t *testing.T) {
func TestHTTPProxy(t *testing.T) {
c, err := net.Listen("tcp", "localhost:0")
if err != nil {
t.Fatal(err)
@@ -47,7 +47,7 @@ func TestHTTPRouter(t *testing.T) {
http.Handle("/", new(testHandler))
// new proxy
p := NewSingleHostRouter(url)
p := NewSingleHostProxy(url)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
@@ -91,32 +91,3 @@ func TestHTTPRouter(t *testing.T) {
}
}
}
func TestHTTPRouterOptions(t *testing.T) {
// test endpoint
service := NewService(
WithBackend("http://foo.bar"),
)
r := service.Server().Options().Router
httpRouter, ok := r.(*Router)
if !ok {
t.Fatal("Expected http router to be installed")
}
if httpRouter.Backend != "http://foo.bar" {
t.Fatalf("Expected endpoint http://foo.bar got %v", httpRouter.Backend)
}
// test router
service = NewService(
WithRouter(&Router{Backend: "http://foo2.bar"}),
)
r = service.Server().Options().Router
httpRouter, ok = r.(*Router)
if !ok {
t.Fatal("Expected http router to be installed")
}
if httpRouter.Backend != "http://foo2.bar" {
t.Fatalf("Expected endpoint http://foo2.bar got %v", httpRouter.Backend)
}
}

325
network/proxy/mucp/mucp.go Normal file
View File

@@ -0,0 +1,325 @@
// Package mucp transparently forwards the incoming request using a go-micro client.
package mucp
import (
"context"
"fmt"
"io"
"strings"
"sync"
"github.com/micro/go-micro/client"
"github.com/micro/go-micro/codec"
"github.com/micro/go-micro/codec/bytes"
"github.com/micro/go-micro/config/options"
"github.com/micro/go-micro/network/proxy"
"github.com/micro/go-micro/network/router"
"github.com/micro/go-micro/server"
)
// Proxy will transparently proxy requests to an endpoint.
// If no endpoint is specified it will call a service using the client.
type Proxy struct {
// embed options
options.Options
// Endpoint specifies the fixed service endpoint to call.
Endpoint string
// The client to use for outbound requests
Client client.Client
// The router for routes
Router router.Router
// A fib of routes service:address
sync.RWMutex
Routes map[string]map[uint64]router.Route
// The channel to monitor watcher errors
errChan chan error
}
// read client request and write to server
func readLoop(r server.Request, s client.Stream) error {
// request to backend server
req := s.Request()
for {
// get data from client
// no need to decode it
body, err := r.Read()
if err == io.EOF {
return nil
}
if err != nil {
return err
}
// get the header from client
hdr := r.Header()
msg := &codec.Message{
Type: codec.Request,
Header: hdr,
Body: body,
}
// write the raw request
err = req.Codec().Write(msg, nil)
if err == io.EOF {
return nil
} else if err != nil {
return err
}
}
}
// toNodes returns a list of node addresses from given routes
func toNodes(routes map[uint64]router.Route) []string {
var nodes []string
for _, node := range routes {
address := node.Address
if len(node.Gateway) > 0 {
address = node.Gateway
}
nodes = append(nodes, address)
}
return nodes
}
func (p *Proxy) getRoute(service string) ([]string, error) {
// lookup the route cache first
p.Lock()
routes, ok := p.Routes[service]
if ok {
p.Unlock()
return toNodes(routes), nil
}
p.Routes[service] = make(map[uint64]router.Route)
p.Unlock()
// if the router is broken return error
if status := p.Router.Status(); status.Code == router.Error {
return nil, status.Error
}
// lookup the routes in the router
results, err := p.Router.Lookup(router.NewQuery(router.QueryService(service)))
if err != nil {
return nil, err
}
// update the proxy cache
p.Lock()
for _, route := range results {
p.Routes[service][route.Hash()] = route
}
routes = p.Routes[service]
p.Unlock()
return toNodes(routes), nil
}
// manageRouteCache applies action on a given route to Proxy route cache
func (p *Proxy) manageRouteCache(route router.Route, action string) error {
switch action {
case "create", "update":
if _, ok := p.Routes[route.Service]; !ok {
p.Routes[route.Service] = make(map[uint64]router.Route)
}
p.Routes[route.Service][route.Hash()] = route
case "delete":
if _, ok := p.Routes[route.Service]; !ok {
return fmt.Errorf("route not found")
}
delete(p.Routes[route.Service], route.Hash())
default:
return fmt.Errorf("unknown action: %s", action)
}
return nil
}
// watchRoutes watches service routes and updates proxy cache
func (p *Proxy) watchRoutes() {
// this is safe to do as the only way watchRoutes returns is
// when some error is written into error channel - we want to bail then
defer close(p.errChan)
// route watcher
w, err := p.Router.Watch()
if err != nil {
p.errChan <- err
return
}
for {
event, err := w.Next()
if err != nil {
p.errChan <- err
return
}
p.Lock()
if err := p.manageRouteCache(event.Route, fmt.Sprintf("%s", event.Type)); err != nil {
// TODO: should we bail here?
p.Unlock()
continue
}
p.Unlock()
}
}
// ServeRequest honours the server.Router interface
func (p *Proxy) ServeRequest(ctx context.Context, req server.Request, rsp server.Response) error {
// service name
service := req.Service()
endpoint := req.Endpoint()
var addresses []string
// call a specific backend endpoint either by name or address
if len(p.Endpoint) > 0 {
// address:port
if parts := strings.Split(p.Endpoint, ":"); len(parts) > 1 {
addresses = []string{p.Endpoint}
} else {
// get route for endpoint from router
addr, err := p.getRoute(p.Endpoint)
if err != nil {
return err
}
// set the address
addresses = addr
// set the name
service = p.Endpoint
}
} else {
// no endpoint was specified just lookup the route
// get route for endpoint from router
addr, err := p.getRoute(service)
if err != nil {
return err
}
addresses = addr
}
var opts []client.CallOption
// set address if available
if len(addresses) > 0 {
opts = append(opts, client.WithAddress(addresses...))
}
// read initial request
body, err := req.Read()
if err != nil {
return err
}
// create new request with raw bytes body
creq := p.Client.NewRequest(service, endpoint, &bytes.Frame{body}, client.WithContentType(req.ContentType()))
// create new stream
stream, err := p.Client.Stream(ctx, creq, opts...)
if err != nil {
return err
}
defer stream.Close()
// create client request read loop
go readLoop(req, stream)
// get raw response
resp := stream.Response()
// route watcher error
var watchErr error
// create server response write loop
for {
select {
case err := <-p.errChan:
if err != nil {
watchErr = err
}
return watchErr
default:
// read backend response body
body, err := resp.Read()
if err == io.EOF {
return nil
} else if err != nil {
return err
}
// read backend response header
hdr := resp.Header()
// write raw response header to client
rsp.WriteHeader(hdr)
// write raw response body to client
err = rsp.Write(body)
if err == io.EOF {
return nil
} else if err != nil {
return err
}
}
}
return nil
}
// NewSingleHostProxy returns a proxy which sends requests to a single backend
func NewSingleHostProxy(endpoint string) *Proxy {
return &Proxy{
Options: options.NewOptions(),
Endpoint: endpoint,
}
}
// NewProxy returns a new proxy which will route based on mucp headers
func NewProxy(opts ...options.Option) proxy.Proxy {
p := new(Proxy)
p.Options = options.NewOptions(opts...)
p.Options.Init(options.WithString("mucp"))
// get endpoint
ep, ok := p.Options.Values().Get("proxy.endpoint")
if ok {
p.Endpoint = ep.(string)
}
// get client
c, ok := p.Options.Values().Get("proxy.client")
if ok {
p.Client = c.(client.Client)
}
// set the default client
if p.Client == nil {
p.Client = client.DefaultClient
}
// get router
r, ok := p.Options.Values().Get("proxy.router")
if ok {
p.Router = r.(router.Router)
}
// create default router and start it
if p.Router == nil {
p.Router = router.DefaultRouter
}
// routes cache
p.Routes = make(map[string]map[uint64]router.Route)
// watch router service routes
p.errChan = make(chan error, 1)
go p.watchRoutes()
return p
}

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