github.com/hashicorp/go-plugin@v1.6.0/examples/grpc/shared/interface.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  // Package shared contains shared data between the host and plugins.
     5  package shared
     6  
     7  import (
     8  	"context"
     9  	"net/rpc"
    10  
    11  	"google.golang.org/grpc"
    12  
    13  	"github.com/hashicorp/go-plugin"
    14  	"github.com/hashicorp/go-plugin/examples/grpc/proto"
    15  )
    16  
    17  // Handshake is a common handshake that is shared by plugin and host.
    18  var Handshake = plugin.HandshakeConfig{
    19  	// This isn't required when using VersionedPlugins
    20  	ProtocolVersion:  1,
    21  	MagicCookieKey:   "BASIC_PLUGIN",
    22  	MagicCookieValue: "hello",
    23  }
    24  
    25  // PluginMap is the map of plugins we can dispense.
    26  var PluginMap = map[string]plugin.Plugin{
    27  	"kv_grpc": &KVGRPCPlugin{},
    28  	"kv":      &KVPlugin{},
    29  }
    30  
    31  // KV is the interface that we're exposing as a plugin.
    32  type KV interface {
    33  	Put(key string, value []byte) error
    34  	Get(key string) ([]byte, error)
    35  }
    36  
    37  // This is the implementation of plugin.Plugin so we can serve/consume this.
    38  type KVPlugin struct {
    39  	// Concrete implementation, written in Go. This is only used for plugins
    40  	// that are written in Go.
    41  	Impl KV
    42  }
    43  
    44  func (p *KVPlugin) Server(*plugin.MuxBroker) (interface{}, error) {
    45  	return &RPCServer{Impl: p.Impl}, nil
    46  }
    47  
    48  func (*KVPlugin) Client(b *plugin.MuxBroker, c *rpc.Client) (interface{}, error) {
    49  	return &RPCClient{client: c}, nil
    50  }
    51  
    52  // This is the implementation of plugin.GRPCPlugin so we can serve/consume this.
    53  type KVGRPCPlugin struct {
    54  	// GRPCPlugin must still implement the Plugin interface
    55  	plugin.Plugin
    56  	// Concrete implementation, written in Go. This is only used for plugins
    57  	// that are written in Go.
    58  	Impl KV
    59  }
    60  
    61  func (p *KVGRPCPlugin) GRPCServer(broker *plugin.GRPCBroker, s *grpc.Server) error {
    62  	proto.RegisterKVServer(s, &GRPCServer{Impl: p.Impl})
    63  	return nil
    64  }
    65  
    66  func (p *KVGRPCPlugin) GRPCClient(ctx context.Context, broker *plugin.GRPCBroker, c *grpc.ClientConn) (interface{}, error) {
    67  	return &GRPCClient{client: proto.NewKVClient(c)}, nil
    68  }