/
plugin.go
378 lines (320 loc) · 13.4 KB
/
plugin.go
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
package resource
import (
"context"
"fmt"
"io/ioutil"
"os"
"strings"
"sync"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/terraform-exec/tfexec"
"github.com/hashicorp/terraform-plugin-go/tfprotov5"
"github.com/hashicorp/terraform-plugin-go/tfprotov6"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging"
"github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugintest"
"github.com/hashicorp/terraform-plugin-sdk/v2/plugin"
testing "github.com/mitchellh/go-testing-interface"
)
type providerFactories struct {
legacy map[string]func() (*schema.Provider, error)
protov5 map[string]func() (tfprotov5.ProviderServer, error)
protov6 map[string]func() (tfprotov6.ProviderServer, error)
}
func runProviderCommand(ctx context.Context, t testing.T, f func() error, wd *plugintest.WorkingDir, factories providerFactories) error {
// don't point to this as a test failure location
// point to whatever called it
t.Helper()
// Run the providers in the same process as the test runner using the
// reattach behavior in Terraform. This ensures we get test coverage
// and enables the use of delve as a debugger.
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// this is needed so Terraform doesn't default to expecting protocol 4;
// we're skipping the handshake because Terraform didn't launch the
// plugins.
os.Setenv("PLUGIN_PROTOCOL_VERSIONS", "5")
// Acceptance testing does not need to call checkpoint as the output
// is not accessible, nor desirable if explicitly using
// TF_ACC_TERRAFORM_PATH or TF_ACC_TERRAFORM_VERSION environment variables.
//
// Avoid calling (tfexec.Terraform).SetEnv() as it will stop copying
// os.Environ() and prevents TF_VAR_ environment variable usage.
os.Setenv("CHECKPOINT_DISABLE", "1")
// Terraform 0.12.X and 0.13.X+ treat namespaceless providers
// differently in terms of what namespace they default to. So we're
// going to set both variations, as we don't know which version of
// Terraform we're talking to. We're also going to allow overriding
// the host or namespace using environment variables.
var namespaces []string
host := "registry.terraform.io"
if v := os.Getenv(EnvTfAccProviderNamespace); v != "" {
namespaces = append(namespaces, v)
} else {
namespaces = append(namespaces, "-", "hashicorp")
}
if v := os.Getenv(EnvTfAccProviderHost); v != "" {
host = v
}
// Spin up gRPC servers for every provider factory, start a
// WaitGroup to listen for all of the close channels.
var wg sync.WaitGroup
reattachInfo := map[string]tfexec.ReattachConfig{}
for providerName, factory := range factories.legacy {
// providerName may be returned as terraform-provider-foo, and
// we need just foo. So let's fix that.
providerName = strings.TrimPrefix(providerName, "terraform-provider-")
providerAddress := getProviderAddr(providerName)
logging.HelperResourceDebug(ctx, "Creating sdkv2 provider instance", map[string]interface{}{logging.KeyProviderAddress: providerAddress})
provider, err := factory()
if err != nil {
return fmt.Errorf("unable to create provider %q from factory: %w", providerName, err)
}
logging.HelperResourceDebug(ctx, "Created sdkv2 provider instance", map[string]interface{}{logging.KeyProviderAddress: providerAddress})
// keep track of the running factory, so we can make sure it's
// shut down.
wg.Add(1)
// configure the settings our plugin will be served with
// the GRPCProviderFunc wraps a non-gRPC provider server
// into a gRPC interface, and the logger just discards logs
// from go-plugin.
opts := &plugin.ServeOpts{
GRPCProviderFunc: func() tfprotov5.ProviderServer {
return schema.NewGRPCProviderServer(provider)
},
Logger: hclog.New(&hclog.LoggerOptions{
Name: "plugintest",
Level: hclog.Trace,
Output: ioutil.Discard,
}),
NoLogOutputOverride: true,
UseTFLogSink: t,
ProviderAddr: providerAddress,
}
logging.HelperResourceDebug(ctx, "Starting sdkv2 provider instance server", map[string]interface{}{logging.KeyProviderAddress: providerAddress})
config, closeCh, err := plugin.DebugServe(ctx, opts)
if err != nil {
return fmt.Errorf("unable to serve provider %q: %w", providerName, err)
}
logging.HelperResourceDebug(ctx, "Started sdkv2 provider instance server", map[string]interface{}{logging.KeyProviderAddress: providerAddress})
tfexecConfig := tfexec.ReattachConfig{
Protocol: config.Protocol,
ProtocolVersion: config.ProtocolVersion,
Pid: config.Pid,
Test: config.Test,
Addr: tfexec.ReattachConfigAddr{
Network: config.Addr.Network,
String: config.Addr.String,
},
}
// when the provider exits, remove one from the waitgroup
// so we can track when everything is done
go func(c <-chan struct{}) {
<-c
wg.Done()
}(closeCh)
// set our provider's reattachinfo in our map, once
// for every namespace that different Terraform versions
// may expect.
for _, ns := range namespaces {
reattachInfo[strings.TrimSuffix(host, "/")+"/"+
strings.TrimSuffix(ns, "/")+"/"+
providerName] = tfexecConfig
}
}
// Now spin up gRPC servers for every protov5 provider factory
// in the same way.
for providerName, factory := range factories.protov5 {
// providerName may be returned as terraform-provider-foo, and
// we need just foo. So let's fix that.
providerName = strings.TrimPrefix(providerName, "terraform-provider-")
providerAddress := getProviderAddr(providerName)
// If the user has supplied the same provider in both
// ProviderFactories and ProtoV5ProviderFactories, they made a
// mistake and we should exit early.
for _, ns := range namespaces {
reattachString := strings.TrimSuffix(host, "/") + "/" +
strings.TrimSuffix(ns, "/") + "/" +
providerName
if _, ok := reattachInfo[reattachString]; ok {
return fmt.Errorf("Provider %s registered in both TestCase.ProviderFactories and TestCase.ProtoV5ProviderFactories: please use one or the other, or supply a muxed provider to TestCase.ProtoV5ProviderFactories.", providerName)
}
}
logging.HelperResourceDebug(ctx, "Creating tfprotov5 provider instance", map[string]interface{}{logging.KeyProviderAddress: providerAddress})
provider, err := factory()
if err != nil {
return fmt.Errorf("unable to create provider %q from factory: %w", providerName, err)
}
logging.HelperResourceDebug(ctx, "Created tfprotov5 provider instance", map[string]interface{}{logging.KeyProviderAddress: providerAddress})
// keep track of the running factory, so we can make sure it's
// shut down.
wg.Add(1)
// configure the settings our plugin will be served with
// the GRPCProviderFunc wraps a non-gRPC provider server
// into a gRPC interface, and the logger just discards logs
// from go-plugin.
opts := &plugin.ServeOpts{
GRPCProviderFunc: func() tfprotov5.ProviderServer {
return provider
},
Logger: hclog.New(&hclog.LoggerOptions{
Name: "plugintest",
Level: hclog.Trace,
Output: ioutil.Discard,
}),
NoLogOutputOverride: true,
UseTFLogSink: t,
ProviderAddr: providerAddress,
}
logging.HelperResourceDebug(ctx, "Starting tfprotov5 provider instance server", map[string]interface{}{logging.KeyProviderAddress: providerAddress})
config, closeCh, err := plugin.DebugServe(ctx, opts)
if err != nil {
return fmt.Errorf("unable to serve provider %q: %w", providerName, err)
}
logging.HelperResourceDebug(ctx, "Started tfprotov5 provider instance server", map[string]interface{}{logging.KeyProviderAddress: providerAddress})
tfexecConfig := tfexec.ReattachConfig{
Protocol: config.Protocol,
ProtocolVersion: config.ProtocolVersion,
Pid: config.Pid,
Test: config.Test,
Addr: tfexec.ReattachConfigAddr{
Network: config.Addr.Network,
String: config.Addr.String,
},
}
// when the provider exits, remove one from the waitgroup
// so we can track when everything is done
go func(c <-chan struct{}) {
<-c
wg.Done()
}(closeCh)
// set our provider's reattachinfo in our map, once
// for every namespace that different Terraform versions
// may expect.
for _, ns := range namespaces {
reattachString := strings.TrimSuffix(host, "/") + "/" +
strings.TrimSuffix(ns, "/") + "/" +
providerName
reattachInfo[reattachString] = tfexecConfig
}
}
// Now spin up gRPC servers for every protov6 provider factory
// in the same way.
for providerName, factory := range factories.protov6 {
// providerName may be returned as terraform-provider-foo, and
// we need just foo. So let's fix that.
providerName = strings.TrimPrefix(providerName, "terraform-provider-")
providerAddress := getProviderAddr(providerName)
// If the user has already registered this provider in
// ProviderFactories or ProtoV5ProviderFactories, they made a
// mistake and we should exit early.
for _, ns := range namespaces {
reattachString := strings.TrimSuffix(host, "/") + "/" +
strings.TrimSuffix(ns, "/") + "/" +
providerName
if _, ok := reattachInfo[reattachString]; ok {
return fmt.Errorf("Provider %s registered in both TestCase.ProtoV6ProviderFactories and either TestCase.ProviderFactories or TestCase.ProtoV5ProviderFactories: please use one of the three, or supply a muxed provider to TestCase.ProtoV5ProviderFactories.", providerName)
}
}
logging.HelperResourceDebug(ctx, "Creating tfprotov6 provider instance", map[string]interface{}{logging.KeyProviderAddress: providerAddress})
provider, err := factory()
if err != nil {
return fmt.Errorf("unable to create provider %q from factory: %w", providerName, err)
}
logging.HelperResourceDebug(ctx, "Created tfprotov6 provider instance", map[string]interface{}{logging.KeyProviderAddress: providerAddress})
// keep track of the running factory, so we can make sure it's
// shut down.
wg.Add(1)
opts := &plugin.ServeOpts{
GRPCProviderV6Func: func() tfprotov6.ProviderServer {
return provider
},
Logger: hclog.New(&hclog.LoggerOptions{
Name: "plugintest",
Level: hclog.Trace,
Output: ioutil.Discard,
}),
NoLogOutputOverride: true,
UseTFLogSink: t,
ProviderAddr: providerAddress,
}
logging.HelperResourceDebug(ctx, "Starting tfprotov6 provider instance server", map[string]interface{}{logging.KeyProviderAddress: providerAddress})
config, closeCh, err := plugin.DebugServe(ctx, opts)
if err != nil {
return fmt.Errorf("unable to serve provider %q: %w", providerName, err)
}
logging.HelperResourceDebug(ctx, "Started tfprotov6 provider instance server", map[string]interface{}{logging.KeyProviderAddress: providerAddress})
tfexecConfig := tfexec.ReattachConfig{
Protocol: config.Protocol,
ProtocolVersion: config.ProtocolVersion,
Pid: config.Pid,
Test: config.Test,
Addr: tfexec.ReattachConfigAddr{
Network: config.Addr.Network,
String: config.Addr.String,
},
}
// when the provider exits, remove one from the waitgroup
// so we can track when everything is done
go func(c <-chan struct{}) {
<-c
wg.Done()
}(closeCh)
// set our provider's reattachinfo in our map, once
// for every namespace that different Terraform versions
// may expect.
for _, ns := range namespaces {
reattachString := strings.TrimSuffix(host, "/") + "/" +
strings.TrimSuffix(ns, "/") + "/" +
providerName
reattachInfo[reattachString] = tfexecConfig
}
}
// set the working directory reattach info that will tell Terraform how to
// connect to our various running servers.
wd.SetReattachInfo(ctx, reattachInfo)
logging.HelperResourceTrace(ctx, "Calling wrapped Terraform CLI command")
// ok, let's call whatever Terraform command the test was trying to
// call, now that we know it'll attach back to those servers we just
// started.
err := f()
if err != nil {
logging.HelperResourceWarn(ctx, "Error running Terraform CLI command", map[string]interface{}{logging.KeyError: err})
}
logging.HelperResourceTrace(ctx, "Called wrapped Terraform CLI command")
logging.HelperResourceDebug(ctx, "Stopping providers")
// cancel the servers so they'll return. Otherwise, this closeCh won't
// get closed, and we'll hang here.
cancel()
logging.HelperResourceTrace(ctx, "Waiting for providers to stop")
// wait for the servers to actually shut down; it may take a moment for
// them to clean up, or whatever.
// TODO: add a timeout here?
// PC: do we need one? The test will time out automatically...
wg.Wait()
logging.HelperResourceTrace(ctx, "Providers have successfully stopped")
// once we've run the Terraform command, let's remove the reattach
// information from the WorkingDir's environment. The WorkingDir will
// persist until the next call, but the server in the reattach info
// doesn't exist anymore at this point, so the reattach info is no
// longer valid. In theory it should be overwritten in the next call,
// but just to avoid any confusing bug reports, let's just unset the
// environment variable altogether.
wd.UnsetReattachInfo()
// return any error returned from the orchestration code running
// Terraform commands
return err
}
func getProviderAddr(name string) string {
host := "registry.terraform.io"
namespace := "hashicorp"
if v := os.Getenv(EnvTfAccProviderNamespace); v != "" {
namespace = v
}
if v := os.Getenv(EnvTfAccProviderHost); v != "" {
host = v
}
return strings.TrimSuffix(host, "/") + "/" +
strings.TrimSuffix(namespace, "/") + "/" +
name
}