github.com/rothwerx/packer@v0.9.0/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  	mux    *muxBroker
    14  }
    15  
    16  // HookServer wraps a packer.Hook implementation and makes it exportable
    17  // as part of a Golang RPC server.
    18  type HookServer struct {
    19  	hook packer.Hook
    20  	mux  *muxBroker
    21  }
    22  
    23  type HookRunArgs struct {
    24  	Name     string
    25  	Data     interface{}
    26  	StreamId uint32
    27  }
    28  
    29  func (h *hook) Run(name string, ui packer.Ui, comm packer.Communicator, data interface{}) error {
    30  	nextId := h.mux.NextId()
    31  	server := newServerWithMux(h.mux, nextId)
    32  	server.RegisterCommunicator(comm)
    33  	server.RegisterUi(ui)
    34  	go server.Serve()
    35  
    36  	args := HookRunArgs{
    37  		Name:     name,
    38  		Data:     data,
    39  		StreamId: nextId,
    40  	}
    41  
    42  	return h.client.Call("Hook.Run", &args, new(interface{}))
    43  }
    44  
    45  func (h *hook) Cancel() {
    46  	err := h.client.Call("Hook.Cancel", new(interface{}), new(interface{}))
    47  	if err != nil {
    48  		log.Printf("Hook.Cancel error: %s", err)
    49  	}
    50  }
    51  
    52  func (h *HookServer) Run(args *HookRunArgs, reply *interface{}) error {
    53  	client, err := newClientWithMux(h.mux, args.StreamId)
    54  	if err != nil {
    55  		return NewBasicError(err)
    56  	}
    57  	defer client.Close()
    58  
    59  	if err := h.hook.Run(args.Name, client.Ui(), client.Communicator(), args.Data); err != nil {
    60  		return NewBasicError(err)
    61  	}
    62  
    63  	*reply = nil
    64  	return nil
    65  }
    66  
    67  func (h *HookServer) Cancel(args *interface{}, reply *interface{}) error {
    68  	h.hook.Cancel()
    69  	return nil
    70  }