github.com/terramate-io/tf@v0.0.0-20230830114523-fce866b4dfcd/plugin6/serve.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  package plugin6
     5  
     6  import (
     7  	"github.com/hashicorp/go-plugin"
     8  	proto "github.com/terramate-io/tf/tfplugin6"
     9  )
    10  
    11  const (
    12  	// The constants below are the names of the plugins that can be dispensed
    13  	// from the plugin server.
    14  	ProviderPluginName = "provider"
    15  
    16  	// DefaultProtocolVersion is the protocol version assumed for legacy clients
    17  	// that don't specify a particular version during their handshake. Since we
    18  	// explicitly set VersionedPlugins in Serve, this number does not need to
    19  	// change with the protocol version and can effectively stay 4 forever
    20  	// (unless we need the "biggest hammer" approach to break all provider
    21  	// compatibility).
    22  	DefaultProtocolVersion = 4
    23  )
    24  
    25  // Handshake is the HandshakeConfig used to configure clients and servers.
    26  var Handshake = plugin.HandshakeConfig{
    27  	// The ProtocolVersion is the version that must match between TF core
    28  	// and TF plugins.
    29  	ProtocolVersion: DefaultProtocolVersion,
    30  
    31  	// The magic cookie values should NEVER be changed.
    32  	MagicCookieKey:   "TF_PLUGIN_MAGIC_COOKIE",
    33  	MagicCookieValue: "d602bf8f470bc67ca7faa0386276bbdd4330efaf76d1a219cb4d6991ca9872b2",
    34  }
    35  
    36  type GRPCProviderFunc func() proto.ProviderServer
    37  
    38  // ServeOpts are the configurations to serve a plugin.
    39  type ServeOpts struct {
    40  	GRPCProviderFunc GRPCProviderFunc
    41  }
    42  
    43  // Serve serves a plugin. This function never returns and should be the final
    44  // function called in the main function of the plugin.
    45  func Serve(opts *ServeOpts) {
    46  	plugin.Serve(&plugin.ServeConfig{
    47  		HandshakeConfig:  Handshake,
    48  		VersionedPlugins: pluginSet(opts),
    49  		GRPCServer:       plugin.DefaultGRPCServer,
    50  	})
    51  }
    52  
    53  func pluginSet(opts *ServeOpts) map[int]plugin.PluginSet {
    54  	plugins := map[int]plugin.PluginSet{}
    55  
    56  	// add the new protocol versions if they're configured
    57  	if opts.GRPCProviderFunc != nil {
    58  		plugins[6] = plugin.PluginSet{}
    59  		if opts.GRPCProviderFunc != nil {
    60  			plugins[6]["provider"] = &GRPCProviderPlugin{
    61  				GRPCProvider: opts.GRPCProviderFunc,
    62  			}
    63  		}
    64  	}
    65  	return plugins
    66  }