-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathprovider.go
353 lines (285 loc) · 9.82 KB
/
provider.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
// Mostly adapted from tfschema - https://github.com/minamijoyo/tfschema
package tfstructs
import (
"fmt"
//log "github.com/sirupsen/logrus"
"encoding/json"
"go/build"
"io/ioutil"
oldLog "log"
"os"
"os/exec"
"path/filepath"
"reflect"
"runtime"
"strings"
internalPlugin "github.com/hashicorp/go-plugin"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/hashicorp/terraform/plugin"
"github.com/hashicorp/terraform/plugin/discovery"
"github.com/hashicorp/terraform/providers"
"github.com/hashicorp/terraform/provisioners"
"github.com/mitchellh/go-homedir"
)
var internalProvisionerList = map[string]bool{
"chef": true,
"file": true,
"habitat": true,
"local-exec": true,
"puppet": true,
"remote-exec": true,
"salt-masterless": true,
}
// Client represents a tfschema Client.
type Client struct {
provider *plugin.GRPCProvider
provisioner *plugin.GRPCProvisioner
pluginClient interface{}
}
// NewProvisionerClient creates a new Client instance for Provisioner.
func NewProvisionerClient(name string, targetDir string) (*Client, error) {
// find a provisioner plugin
if !internalProvisionerList[name] {
pluginMeta, err := findPlugin("provisioner", name, targetDir)
if err != nil {
return nil, err
}
pluginClient := plugin.Client(*pluginMeta)
rpcClient, err2 := pluginClient.Client()
if err2 != nil {
return nil, fmt.Errorf("Failed to initialize plugin: %s", err2)
}
// create a new resource provisioner.
raw, err := rpcClient.Dispense(plugin.ProvisionerPluginName)
if err != nil {
return nil, fmt.Errorf("Failed to dispense plugin: %s", err)
}
provisioner := raw.(*plugin.GRPCProvisioner)
return &Client{
provisioner: provisioner,
pluginClient: pluginClient,
}, nil
} else {
// initialize a plugin Client.
pluginClientConfig := plugin.ClientConfig(discovery.PluginMeta{
Name: "terraform",
})
res, _ := exec.LookPath("terraform")
pluginClientConfig.Cmd = exec.Command(res, "internal-plugin", "provisioner", name)
pluginClient := internalPlugin.NewClient(pluginClientConfig)
var err error
rpcClient, err := pluginClient.Client()
if err != nil {
return nil, fmt.Errorf("Failed to initialize plugin: %s", err)
}
// create a new resource provisioner.
raw, err := rpcClient.Dispense(plugin.ProvisionerPluginName)
if err != nil {
return nil, fmt.Errorf("Failed to dispense plugin: %s", err)
}
provisioner := raw.(*plugin.GRPCProvisioner)
return &Client{
provisioner: provisioner,
pluginClient: pluginClient,
}, nil
}
}
// NewClient creates a new Client instance.
func NewClient(providerName string, targetDir string) (*Client, error) {
// find a provider plugin
pluginMeta, err := findPlugin("provider", providerName, targetDir)
if err != nil {
return nil, err
}
clientName := fmt.Sprintf("%s_%s", pluginMeta.Name, pluginMeta.Version)
// initialize a plugin Client.
var finalClient *Client
if Clients[clientName] == nil {
pluginClient := plugin.Client(*pluginMeta)
rpcClient, err := pluginClient.Client()
if err != nil {
return nil, fmt.Errorf("Failed to initialize plugin: %s", err)
}
// create a new resource provider.
raw, err := rpcClient.Dispense(plugin.ProviderPluginName)
if err != nil {
return nil, fmt.Errorf("Failed to dispense plugin: %s", err)
}
provider := raw.(*plugin.GRPCProvider)
finalClient = &Client{
provider: provider,
pluginClient: pluginClient,
}
Clients[clientName] = finalClient
} else {
finalClient = Clients[clientName]
}
return finalClient, nil
}
// findPlugin finds a plugin with the name specified in the arguments.
func findPlugin(pluginType string, pluginName string, targetDir string) (*discovery.PluginMeta, error) {
dirs, err := pluginDirs(targetDir)
if err != nil {
return nil, err
}
oldLog.SetOutput(ioutil.Discard)
pluginMetaSet := discovery.FindPlugins(pluginType, dirs).WithName(pluginName)
// if pluginMetaSet doesn't have any pluginMeta, pluginMetaSet.Newest() will call panic.
// so check it here.
if pluginMetaSet.Count() > 0 {
ret := pluginMetaSet.Newest()
return &ret, nil
}
return nil, fmt.Errorf("Failed to find plugin: %s. Plugin binary was not found in any of the following directories: [%s]", pluginName, strings.Join(dirs, ", "))
}
// pluginDirs returns a list of directories to find plugin.
// This is almost the same as Terraform, but not exactly the same.
func pluginDirs(targetDir string) ([]string, error) {
dirs := []string{}
// current directory
dirs = append(dirs, ".")
// same directory as this executable
exePath, err := os.Executable()
if err != nil {
return []string{}, fmt.Errorf("Failed to get executable path: %s", err)
}
dirs = append(dirs, filepath.Dir(exePath))
// user vendor directory
arch := runtime.GOOS + "_" + runtime.GOARCH
vendorDir := filepath.Join("terraform.d", "plugins", arch)
dirs = append(dirs, vendorDir)
// home dir will be searched afterward
homeDir, err := homedir.Dir()
if err != nil {
return []string{}, fmt.Errorf("Failed to get home dir: %s", err)
}
// auto installed directory
// This does not take into account overriding the data directory.
autoInstalledDir := ""
searchLevel := 4
for dir := targetDir; dir != "" && searchLevel != 0; dir = filepath.Dir(dir) {
//log.Debug("[DEBUG] search .terraform dir in %s", dir)
if _, err := os.Stat(filepath.Join(dir, ".terraform")); err == nil {
autoInstalledDir = filepath.Join(dir, ".terraform", "plugins", arch)
if _, err := os.Stat(filepath.Join(dir, ".terraform", "plugins", "selections.json")); err == nil {
selections := make(map[string]interface{})
file, _ := ioutil.ReadFile(filepath.Join(dir, ".terraform", "plugins", "selections.json"))
json.Unmarshal(file, &selections)
for pluginPath, info := range selections {
version := info.(map[string]interface{})["version"]
if _, err := os.Stat(filepath.Join(dir, ".terraform", "plugins", pluginPath, version.(string), arch)); err == nil {
dirs = append(dirs, filepath.Join(dir, ".terraform", "plugins", pluginPath, version.(string), arch))
}
}
}
if _, err := os.Stat(filepath.Join(dir, ".terraform.lock.hcl")); err == nil {
file, _ := ioutil.ReadFile(filepath.Join(dir, ".terraform.lock.hcl"))
lockFile, _ := hclsyntax.ParseConfig(file, ".terraform.lock.hcl", hcl.Pos{
Column: 1,
Line: 1,
})
parsedLock, _ := lockFile.Body.Content(&hcl.BodySchema{
Blocks: []hcl.BlockHeaderSchema{
{
LabelNames: []string{"provider"},
Type: "provider",
},
},
})
for _, provider := range parsedLock.Blocks {
name := []string{
dir,
".terraform",
"providers",
}
name = append(name, strings.Split(provider.Labels[0], "/")...)
vars, _ := provider.Body.JustAttributes()
version := ""
for _, i := range vars {
if i.Name == "version" {
tempVersion, _ := i.Expr.Value(nil)
version = tempVersion.AsString()
}
}
result := append(name, version, arch)
if _, err := os.Stat(filepath.Join(result...)); err == nil {
dirs = append(dirs, filepath.Join(result...))
}
}
}
break
}
searchLevel -= 1
}
if autoInstalledDir != "" {
dirs = append(dirs, autoInstalledDir)
}
// global plugin directory
configDir := filepath.Join(homeDir, ".terraform.d", "plugins")
dirs = append(dirs, configDir)
dirs = append(dirs, filepath.Join(configDir, arch))
// global plugin cache directory
// This does not take into account overriding the plugin cache directory.
cacheDir := filepath.Join(homeDir, ".terraform.d", "plugin-cache", arch)
dirs = append(dirs, cacheDir)
// GOPATH
// This is not included in the Terraform, but for convenience.
gopath := build.Default.GOPATH
dirs = append(dirs, filepath.Join(gopath, "bin"))
//log.Debug("[DEBUG] plugin dirs: %#v", dirs)
return dirs, nil
}
// GetRawProviderSchema returns a raw type definiton of provider schema.
func (c *Client) GetRawProviderSchema() (*providers.Schema, error) {
res := c.provider.GetSchema()
return &res.Provider, nil
}
// GetRawProvisionerSchema returns a raw type definiton of provisioner schema.
func (c *Client) GetRawProvisionerSchema() (*provisioners.GetSchemaResponse, error) {
res := c.provisioner.GetSchema()
return &res, nil
}
// GetRawResourceTypeSchema returns a type definiton of resource type.
func (c *Client) GetRawResourceTypeSchema(resourceType string) (*providers.Schema, error) {
res := c.provider.GetSchema()
if res.ResourceTypes[resourceType].Block == nil {
return nil, fmt.Errorf("Failed to find resource type: %s", resourceType)
}
b := res.ResourceTypes[resourceType]
return &b, nil
}
// GetResourceTypes returns a type definiton of resource type.
func (c *Client) GetResourceTypes() ([]string, error) {
res := c.provider.GetSchema()
var result []string
for k, _ := range res.ResourceTypes {
result = append(result, k)
}
return result, nil
}
// GetDataSourceTypes returns a type definiton of resource type.
func (c *Client) GetDataSourceTypes() ([]string, error) {
res := c.provider.GetSchema()
var result []string
for k, _ := range res.DataSources {
result = append(result, k)
}
return result, nil
}
// GetRawDataSourceTypeSchema returns a type definiton of resource type.
func (c *Client) GetRawDataSourceTypeSchema(dataSourceType string) (*providers.Schema, error) {
res := c.provider.GetSchema()
if res.DataSources[dataSourceType].Block == nil {
return nil, fmt.Errorf("Failed to find data source type: %s", dataSourceType)
}
b := res.DataSources[dataSourceType]
return &b, nil
}
// Kill kills a process of the plugin.
func (c *Client) Kill() {
// We cannot import the vendor version of go-plugin using terraform.
// So, we call (*go-plugin.Client).Kill() by reflection here.
v := reflect.ValueOf(c.pluginClient).MethodByName("Kill")
v.Call([]reflect.Value{})
}