Skip to content

Commit

Permalink
begin refactoring of route manager
Browse files Browse the repository at this point in the history
  • Loading branch information
林志宇 committed Mar 31, 2019
1 parent b071075 commit 1fdf62c
Show file tree
Hide file tree
Showing 13 changed files with 273 additions and 152 deletions.
19 changes: 19 additions & 0 deletions manager-config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"public_key": "039c852257120e750145051da28d543b4ab9a9b37fbc03da0f945a5eb9a9b19884",
"secret_key": "7a9b343805ebc873e16d98806317ba7481372eb3646fd5e39d6f21da1dabbd3d",
"db_path": "/Users/evanlinjin/GolandProjects/skywire/users.db",
"cookies": {
"hash_key": "8376e3a88e69a1432833341e64e4d7ecf130e1ac9c06e2eb7faa89a8f3c32474b0c8b53f34ff56d90fc2e77e883a12adc5a1fac296d7a75d7e2fd1f7e61143cf",
"block_key": "86189a612410794700601226da59e9741b890307c1295bba2b45ca82b1816084",
"expires_duration": 43200000000000,
"path": "/",
"domain": "",
"secure": true,
"http_only": true,
"same_site": 1
},
"interfaces": {
"http_address": ":8080",
"rpc_addr": ":7080"
}
}
2 changes: 1 addition & 1 deletion pkg/router/managed_routing_table.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func (rt *managedRoutingTable) Cleanup() error {
expiredIDs := []routing.RouteID{}
rt.mu.Lock()
err := rt.RangeRules(func(routeID routing.RouteID, rule routing.Rule) bool {
if rule.ExpireAt().Before(time.Now()) {
if rule.Expiry().Before(time.Now()) {
if lastActivity, ok := rt.activity[routeID]; !ok || time.Since(lastActivity) > routeKeepalive {
expiredIDs = append(expiredIDs, routeID)
}
Expand Down
29 changes: 16 additions & 13 deletions pkg/router/route_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ func (rm *routeManager) GetRule(routeID routing.RouteID) (routing.Rule, error) {
return nil, errors.New("unknown RouteID")
}

if rule.ExpireAt().Before(time.Now()) {
if rule.Expiry().Before(time.Now()) {
return nil, errors.New("expired routing rule")
}

Expand Down Expand Up @@ -75,33 +75,36 @@ func (rm *routeManager) RemoveLoopRule(addr *app.LoopAddr) error {

func (rm *routeManager) Serve(rw io.ReadWriter) error {
proto := setup.NewProtocol(rw)
sp, data, err := proto.ReadPacket()
fmt.Println("got proto!")

t, body, err := proto.ReadPacket()
if err != nil {
fmt.Println("err:", err)
return err
}
fmt.Println("read packet!")
rm.Logger.Infof("Got new Setup request with type %s", t)

rm.Logger.Infof("Got new Setup request with type %s", sp)

var res interface{}
switch sp {
var respBody interface{}
switch t {
case setup.PacketAddRules:
res, err = rm.addRoutingRules(data)
respBody, err = rm.addRoutingRules(body)
case setup.PacketDeleteRules:
res, err = rm.deleteRoutingRules(data)
respBody, err = rm.deleteRoutingRules(body)
case setup.PacketConfirmLoop:
res, err = rm.confirmLoop(data)
respBody, err = rm.confirmLoop(body)
case setup.PacketLoopClosed:
err = rm.loopClosed(data)
err = rm.loopClosed(body)
default:
err = errors.New("unknown foundation packet")
}

if err != nil {
rm.Logger.Infof("Setup request with type %s failed: %s", sp, err)
return proto.Respond(err)
rm.Logger.Infof("Setup request with type %s failed: %s", t, err)
return proto.WritePacket(setup.RespFailure, err.Error())
}

return proto.Respond(res)
return proto.WritePacket(setup.RespSuccess, respBody)
}

func (rm *routeManager) addRoutingRules(data []byte) ([]routing.RouteID, error) {
Expand Down
26 changes: 22 additions & 4 deletions pkg/router/route_manager_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package router

import (
"fmt"
"net"
"testing"
"time"
Expand Down Expand Up @@ -58,19 +59,36 @@ func TestRouteManagerRemoveLoopRule(t *testing.T) {
}

func TestRouteManagerAddRemoveRule(t *testing.T) {
fmt.Println("start!")
done := make(chan struct{})
expired := time.NewTimer(time.Second * 5)
go func() {
select {
case <-done:
fmt.Println("done!")
return
case <-expired.C:
fmt.Println("expired!")
}
}()
defer func() {
close(done)
}()
rt := manageRoutingTable(routing.InMemoryRoutingTable())
rm := &routeManager{logging.MustGetLogger("routesetup"), rt, nil}

in, out := net.Pipe()
errCh := make(chan error)
go func() {
fmt.Println("watiting serve...")
errCh <- rm.Serve(out)
fmt.Println("DONE!")
}()

proto := setup.NewProtocol(in)

rule := routing.ForwardRule(time.Now(), 3, uuid.New())
id, err := proto.AddRule(rule)
id, err := setup.AddRule(proto, rule)
require.NoError(t, err)
assert.Equal(t, routing.RouteID(1), id)

Expand Down Expand Up @@ -100,7 +118,7 @@ func TestRouteManagerDeleteRules(t *testing.T) {
require.NoError(t, err)
assert.Equal(t, 1, rt.Count())

require.NoError(t, proto.DeleteRule(id))
require.NoError(t, setup.DeleteRule(proto, id))
assert.Equal(t, 0, rt.Count())

require.NoError(t, in.Close())
Expand Down Expand Up @@ -143,7 +161,7 @@ func TestRouteManagerConfirmLoop(t *testing.T) {
RouteID: 1,
NoiseMessage: []byte("bar"),
}
noiseRes, err := proto.ConfirmLoop(ld)
noiseRes, err := setup.ConfirmLoop(proto, ld)
require.NoError(t, err)
assert.Equal(t, []byte("foo"), noiseRes)
assert.Equal(t, []byte("bar"), noiseMsg)
Expand Down Expand Up @@ -190,7 +208,7 @@ func TestRouteManagerLoopClosed(t *testing.T) {
RouteID: 1,
NoiseMessage: []byte("bar"),
}
require.NoError(t, proto.LoopClosed(ld))
require.NoError(t, setup.LoopClosed(proto, ld))
assert.Equal(t, uint16(2), inAddr.Port)
assert.Equal(t, uint16(3), inAddr.Remote.Port)
assert.Equal(t, pk, inAddr.Remote.PubKey)
Expand Down
6 changes: 3 additions & 3 deletions pkg/router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@ func (r *Router) requestLoop(appConn *app.Protocol, raddr *app.Addr) (*app.Addr,
}

l := &routing.Loop{LocalPort: laddr.Port, RemotePort: raddr.Port,
NoiseMessage: msg, ExpireAt: time.Now().Add(RouteTTL),
NoiseMessage: msg, Expiry: time.Now().Add(RouteTTL),
Forward: forwardRoute, Reverse: reverseRoute}

proto, tr, err := r.setupProto(context.Background())
Expand All @@ -329,7 +329,7 @@ func (r *Router) requestLoop(appConn *app.Protocol, raddr *app.Addr) (*app.Addr,
}
defer tr.Close()

if err := proto.CreateLoop(l); err != nil {
if err := setup.CreateLoop(proto, l); err != nil {
return nil, fmt.Errorf("route setup: %s", err)
}

Expand Down Expand Up @@ -386,7 +386,7 @@ func (r *Router) closeLoop(appConn *app.Protocol, addr *app.LoopAddr) error {
defer tr.Close()

ld := &setup.LoopData{RemotePK: addr.Remote.PubKey, RemotePort: addr.Remote.Port, LocalPort: addr.Port}
if err := proto.CloseLoop(ld); err != nil {
if err := setup.CloseLoop(proto, ld); err != nil {
return fmt.Errorf("route setup: %s", err)
}

Expand Down
22 changes: 11 additions & 11 deletions pkg/router/router_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -323,7 +323,7 @@ func TestRouterSetup(t *testing.T) {

var routeID routing.RouteID
t.Run("add route", func(t *testing.T) {
routeID, err = sProto.AddRule(routing.ForwardRule(time.Now().Add(time.Hour), 2, tr.ID))
routeID, err = setup.AddRule(sProto, routing.ForwardRule(time.Now().Add(time.Hour), 2, tr.ID))
require.NoError(t, err)

rule, err := rt.Rule(routeID)
Expand All @@ -347,10 +347,10 @@ func TestRouterSetup(t *testing.T) {

time.Sleep(100 * time.Millisecond)

appRouteID, err := sProto.AddRule(routing.AppRule(time.Now().Add(time.Hour), 0, pk2, 1, 2))
appRouteID, err := setup.AddRule(sProto, routing.AppRule(time.Now().Add(time.Hour), 0, pk2, 1, 2))
require.NoError(t, err)

noiseRes, err := sProto.ConfirmLoop(&setup.LoopData{RemotePK: pk2, RemotePort: 1, LocalPort: 2, RouteID: routeID, NoiseMessage: msg})
noiseRes, err := setup.ConfirmLoop(sProto, &setup.LoopData{RemotePK: pk2, RemotePort: 1, LocalPort: 2, RouteID: routeID, NoiseMessage: msg})
require.NoError(t, err)

rule, err := rt.Rule(appRouteID)
Expand Down Expand Up @@ -405,10 +405,10 @@ func TestRouterSetup(t *testing.T) {

require.NoError(t, r.pm.SetLoop(4, &app.Addr{PubKey: pk2, Port: 3}, &loop{noise: ni}))

appRouteID, err := sProto.AddRule(routing.AppRule(time.Now().Add(time.Hour), 0, pk2, 3, 4))
appRouteID, err := setup.AddRule(sProto, routing.AppRule(time.Now().Add(time.Hour), 0, pk2, 3, 4))
require.NoError(t, err)

_, err = sProto.ConfirmLoop(&setup.LoopData{RemotePK: pk2, RemotePort: 3, LocalPort: 4, RouteID: routeID, NoiseMessage: noiseRes})
_, err = setup.ConfirmLoop(sProto, &setup.LoopData{RemotePK: pk2, RemotePort: 3, LocalPort: 4, RouteID: routeID, NoiseMessage: noiseRes})
require.NoError(t, err)

rule, err := rt.Rule(appRouteID)
Expand All @@ -435,7 +435,7 @@ func TestRouterSetup(t *testing.T) {
require.NotNil(t, rule)
assert.Equal(t, routing.RuleApp, rule.Type())

require.NoError(t, sProto.LoopClosed(&setup.LoopData{RemotePK: pk2, RemotePort: 3, LocalPort: 4}))
require.NoError(t, setup.LoopClosed(sProto, &setup.LoopData{RemotePK: pk2, RemotePort: 3, LocalPort: 4}))
time.Sleep(100 * time.Millisecond)

_, err = r.pm.GetLoop(4, &app.Addr{PubKey: pk2, Port: 3})
Expand All @@ -449,7 +449,7 @@ func TestRouterSetup(t *testing.T) {
})

t.Run("delete rule", func(t *testing.T) {
require.NoError(t, sProto.DeleteRule(routeID))
require.NoError(t, setup.DeleteRule(sProto, routeID))

rule, err := rt.Rule(routeID)
require.NoError(t, err)
Expand Down Expand Up @@ -513,7 +513,7 @@ func TestRouterSetupLoop(t *testing.T) {
return
}

errCh <- proto.Respond([]byte{})
errCh <- proto.WritePacket(setup.RespSuccess, []byte{})
}()

rw, rwIn := net.Pipe()
Expand Down Expand Up @@ -619,7 +619,7 @@ func TestRouterCloseLoop(t *testing.T) {
return
}

errCh <- proto.Respond([]byte{})
errCh <- proto.WritePacket(setup.RespSuccess, []byte{})
}()

rw, rwIn := net.Pipe()
Expand Down Expand Up @@ -707,7 +707,7 @@ func TestRouterCloseLoopOnAppClose(t *testing.T) {
return
}

errCh <- proto.Respond([]byte{})
errCh <- proto.WritePacket(setup.RespSuccess, []byte{})
}()

rw, rwIn := net.Pipe()
Expand Down Expand Up @@ -793,7 +793,7 @@ func TestRouterCloseLoopOnRouterClose(t *testing.T) {
return
}

errCh <- proto.Respond([]byte{})
errCh <- proto.WritePacket(setup.RespSuccess, []byte{})
}()

rw, rwIn := net.Pipe()
Expand Down
14 changes: 7 additions & 7 deletions pkg/routing/loop.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ import (

// Loop defines a loop over a pair of routes.
type Loop struct {
LocalPort uint16
RemotePort uint16
Forward Route
Reverse Route
ExpireAt time.Time
NoiseMessage []byte
LocalPort uint16 `json:"local_port"`
RemotePort uint16 `json:"remote_port"`
Forward Route `json:"forward_route"`
Reverse Route `json:"reverse_route"`
Expiry time.Time `json:"expiry"`
NoiseMessage []byte `json:"-"`
}

// Initiator returns initiator of the Loop.
Expand All @@ -37,5 +37,5 @@ func (l *Loop) Responder() cipher.PubKey {

func (l *Loop) String() string {
return fmt.Sprintf("lport: %d. rport: %d. routes: %s/%s. expire at %s",
l.LocalPort, l.RemotePort, l.Forward, l.Reverse, l.ExpireAt)
l.LocalPort, l.RemotePort, l.Forward, l.Reverse, l.Expiry)
}
6 changes: 3 additions & 3 deletions pkg/routing/route.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ import (

// Hop defines a route hop between 2 nodes.
type Hop struct {
From cipher.PubKey
To cipher.PubKey
Transport uuid.UUID
From cipher.PubKey `json:"src"`
To cipher.PubKey `json:"dst"`
Transport uuid.UUID `json:"tid"`
}

func (h Hop) String() string {
Expand Down
6 changes: 3 additions & 3 deletions pkg/routing/rule.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ const (
// Rule represents a rule in a RoutingTable.
type Rule []byte

// ExpireAt returns rule's expiration time.
func (r Rule) ExpireAt() time.Time {
// Expiry returns rule's expiration time.
func (r Rule) Expiry() time.Time {
ts := binary.BigEndian.Uint64(r)
return time.Unix(int64(ts), 0)
}
Expand Down Expand Up @@ -140,7 +140,7 @@ func (rs *RuleSummary) ToRule() (Rule, error) {
// Summary returns the RoutingRule's summary.
func (r Rule) Summary() *RuleSummary {
summary := RuleSummary{
ExpireAt: r.ExpireAt(),
ExpireAt: r.Expiry(),
Type: r.Type(),
}
if summary.Type == RuleApp {
Expand Down
4 changes: 2 additions & 2 deletions pkg/routing/rule_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ func TestAppRule(t *testing.T) {
pk, _ := cipher.GenerateKeyPair()
rule := AppRule(expireAt, 2, pk, 3, 4)

assert.Equal(t, expireAt.Unix(), rule.ExpireAt().Unix())
assert.Equal(t, expireAt.Unix(), rule.Expiry().Unix())
assert.Equal(t, RuleApp, rule.Type())
assert.Equal(t, RouteID(2), rule.RouteID())
assert.Equal(t, pk, rule.RemotePK())
Expand All @@ -31,7 +31,7 @@ func TestForwardRule(t *testing.T) {
expireAt := time.Now().Add(2 * time.Minute)
rule := ForwardRule(expireAt, 2, trID)

assert.Equal(t, expireAt.Unix(), rule.ExpireAt().Unix())
assert.Equal(t, expireAt.Unix(), rule.Expiry().Unix())
assert.Equal(t, RuleForward, rule.Type())
assert.Equal(t, RouteID(2), rule.RouteID())
assert.Equal(t, trID, rule.TransportID())
Expand Down
Loading

0 comments on commit 1fdf62c

Please sign in to comment.