aboutsummaryrefslogtreecommitdiffhomepage
path: root/vendor/github.com/hashicorp/terraform/helper/resource/grpc_test_provider.go
blob: 0742e993bc7aba2313eed2d924a42cf21cef707d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package resource

import (
	"context"
	"net"
	"time"

	"github.com/hashicorp/terraform/helper/plugin"
	proto "github.com/hashicorp/terraform/internal/tfplugin5"
	tfplugin "github.com/hashicorp/terraform/plugin"
	"github.com/hashicorp/terraform/providers"
	"github.com/hashicorp/terraform/terraform"
	"google.golang.org/grpc"
	"google.golang.org/grpc/test/bufconn"
)

// GRPCTestProvider takes a legacy ResourceProvider, wraps it in the new GRPC
// shim and starts it in a grpc server using an inmem connection. It returns a
// GRPCClient for this new server to test the shimmed resource provider.
func GRPCTestProvider(rp terraform.ResourceProvider) providers.Interface {
	listener := bufconn.Listen(256 * 1024)
	grpcServer := grpc.NewServer()

	p := plugin.NewGRPCProviderServerShim(rp)
	proto.RegisterProviderServer(grpcServer, p)

	go grpcServer.Serve(listener)

	conn, err := grpc.Dial("", grpc.WithDialer(func(string, time.Duration) (net.Conn, error) {
		return listener.Dial()
	}), grpc.WithInsecure())
	if err != nil {
		panic(err)
	}

	var pp tfplugin.GRPCProviderPlugin
	client, _ := pp.GRPCClient(context.Background(), nil, conn)

	grpcClient := client.(*tfplugin.GRPCProvider)
	grpcClient.TestServer = grpcServer

	return grpcClient
}