rpc: Make a Register function to make working with easier

This commit is contained in:
Mitchell Hashimoto 2014-05-28 15:18:14 -07:00
parent f8dc3286d9
commit 5ef20cf3a2
3 changed files with 39 additions and 6 deletions

View File

@ -8,11 +8,12 @@ import (
type ResourceProvider struct {
Client *rpc.Client
Name string
}
func (p *ResourceProvider) Configure(c map[string]interface{}) ([]string, error) {
var resp ResourceProviderConfigureResponse
err := p.Client.Call("ResourceProvider.Configure", c, &resp)
err := p.Client.Call(p.Name+".Configure", c, &resp)
if err != nil {
return nil, err
}

View File

@ -10,11 +10,11 @@ import (
func TestResourceProvider_configure(t *testing.T) {
p := new(terraform.MockResourceProvider)
client, server := testClientServer(t)
server.RegisterName("ResourceProvider", &ResourceProviderServer{
Provider: p,
})
provider := &ResourceProvider{Client: client}
name, err := Register(server, p)
if err != nil {
t.Fatalf("err: %s", err)
}
provider := &ResourceProvider{Client: client, Name: name}
// Configure
config := map[string]interface{}{"foo": "bar"}

32
rpc/rpc.go Normal file
View File

@ -0,0 +1,32 @@
package rpc
import (
"errors"
"fmt"
"net/rpc"
"sync"
"github.com/hashicorp/terraform/terraform"
)
// nextId is the next ID to use for names registered.
var nextId uint32 = 0
var nextLock sync.Mutex
// Register registers a Terraform thing with the RPC server and returns
// the name it is registered under.
func Register(server *rpc.Server, thing interface{}) (name string, err error) {
nextLock.Lock()
defer nextLock.Unlock()
switch t := thing.(type) {
case terraform.ResourceProvider:
name = fmt.Sprintf("Terraform%d", nextId)
err = server.RegisterName(name, &ResourceProviderServer{Provider: t})
default:
return "", errors.New("Unknown type to register for RPC server.")
}
nextId += 1
return
}