github.com/jerryclinesmith/packer@v0.3.7/packer/rpc/hook.go (about)

     1  package rpc
     2  
     3  import (
     4  	"github.com/mitchellh/packer/packer"
     5  	"log"
     6  	"net/rpc"
     7  )
     8  
     9  // An implementation of packer.Hook where the hook is actually executed
    10  // over an RPC connection.
    11  type hook struct {
    12  	client *rpc.Client
    13  }
    14  
    15  // HookServer wraps a packer.Hook implementation and makes it exportable
    16  // as part of a Golang RPC server.
    17  type HookServer struct {
    18  	hook packer.Hook
    19  }
    20  
    21  type HookRunArgs struct {
    22  	Name       string
    23  	Data       interface{}
    24  	RPCAddress string
    25  }
    26  
    27  func Hook(client *rpc.Client) *hook {
    28  	return &hook{client}
    29  }
    30  
    31  func (h *hook) Run(name string, ui packer.Ui, comm packer.Communicator, data interface{}) error {
    32  	server := rpc.NewServer()
    33  	RegisterCommunicator(server, comm)
    34  	RegisterUi(server, ui)
    35  	address := serveSingleConn(server)
    36  
    37  	args := &HookRunArgs{name, data, address}
    38  	return h.client.Call("Hook.Run", args, new(interface{}))
    39  }
    40  
    41  func (h *hook) Cancel() {
    42  	err := h.client.Call("Hook.Cancel", new(interface{}), new(interface{}))
    43  	if err != nil {
    44  		log.Printf("Hook.Cancel error: %s", err)
    45  	}
    46  }
    47  
    48  func (h *HookServer) Run(args *HookRunArgs, reply *interface{}) error {
    49  	client, err := rpc.Dial("tcp", args.RPCAddress)
    50  	if err != nil {
    51  		return err
    52  	}
    53  
    54  	if err := h.hook.Run(args.Name, &Ui{client}, Communicator(client), args.Data); err != nil {
    55  		return NewBasicError(err)
    56  	}
    57  
    58  	*reply = nil
    59  	return nil
    60  }
    61  
    62  func (h *HookServer) Cancel(args *interface{}, reply *interface{}) error {
    63  	h.hook.Cancel()
    64  	return nil
    65  }