Testing Client RPC to server

pull/19/head
Armon Dadgar 11 years ago
parent c644f1e57b
commit 6a1b36bd46

@ -2,8 +2,10 @@ package consul
import ( import (
"fmt" "fmt"
"github.com/hashicorp/consul/consul/structs"
"github.com/hashicorp/serf/serf" "github.com/hashicorp/serf/serf"
"log" "log"
"math/rand"
"net" "net"
"os" "os"
"path/filepath" "path/filepath"
@ -218,3 +220,21 @@ func (c *Client) nodeFail(me serf.MemberEvent) {
c.consulLock.Unlock() c.consulLock.Unlock()
} }
} }
// RPC is used to forward an RPC call to a consul server, or fail if no servers
func (c *Client) RPC(method string, args interface{}, reply interface{}) error {
// Bail if we can't find any servers
c.consulLock.RLock()
if len(c.consuls) == 0 {
c.consulLock.RUnlock()
return structs.ErrNoServers
}
// Select a random addr
offset := rand.Int31() % int32(len(c.consuls))
server := c.consuls[offset]
c.consulLock.RUnlock()
// Forward to remote Consul
return c.connPool.RPC(server, method, args, reply)
}

@ -2,6 +2,7 @@ package consul
import ( import (
"fmt" "fmt"
"github.com/hashicorp/consul/consul/structs"
"os" "os"
"testing" "testing"
"time" "time"
@ -75,3 +76,42 @@ func TestClient_JoinLAN(t *testing.T) {
t.Fatalf("expected consul server") t.Fatalf("expected consul server")
} }
} }
func TestClient_RPC(t *testing.T) {
dir1, s1 := testServer(t)
defer os.RemoveAll(dir1)
defer s1.Shutdown()
dir2, c1 := testClient(t)
defer os.RemoveAll(dir2)
defer c1.Shutdown()
// Try an RPC
var out struct{}
if err := c1.RPC("Status.Ping", struct{}{}, &out); err != structs.ErrNoServers {
t.Fatalf("err: %v", err)
}
// Try to join
addr := fmt.Sprintf("127.0.0.1:%d",
s1.config.SerfLANConfig.MemberlistConfig.Port)
if err := c1.JoinLAN(addr); err != nil {
t.Fatalf("err: %v", err)
}
// Check the members
if len(s1.LANMembers()) != 2 {
t.Fatalf("bad len")
}
if len(c1.LANMembers()) != 2 {
t.Fatalf("bad len")
}
time.Sleep(10 * time.Millisecond)
// RPC shoudl succeed
if err := c1.RPC("Status.Ping", struct{}{}, &out); err != nil {
t.Fatalf("err: %v", err)
}
}

@ -9,6 +9,7 @@ import (
var ( var (
ErrNoLeader = fmt.Errorf("No cluster leader") ErrNoLeader = fmt.Errorf("No cluster leader")
ErrNoDCPath = fmt.Errorf("No path to datacenter") ErrNoDCPath = fmt.Errorf("No path to datacenter")
ErrNoServers = fmt.Errorf("No known Consul servers")
) )
type MessageType uint8 type MessageType uint8

Loading…
Cancel
Save