github.com/HashDataInc/packer@v1.3.2/packer/rpc/hook.go (about)

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