-
Notifications
You must be signed in to change notification settings - Fork 138
/
Copy pathmodule_manager.go
357 lines (288 loc) · 8.2 KB
/
module_manager.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
package module
import (
"context"
"fmt"
"log"
"os"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/gammazero/workerpool"
"github.com/hashicorp/hcl-lang/schema"
"github.com/hashicorp/terraform-ls/internal/filesystem"
"github.com/hashicorp/terraform-ls/internal/terraform/discovery"
"github.com/hashicorp/terraform-ls/internal/terraform/exec"
)
type moduleManager struct {
modules []*module
newModule ModuleFactory
filesystem filesystem.Filesystem
syncLoading bool
workerPool *workerpool.WorkerPool
logger *log.Logger
// terraform discovery
tfDiscoFunc discovery.DiscoveryFunc
// terraform executor
tfNewExecutor exec.ExecutorFactory
tfExecPath string
tfExecTimeout time.Duration
tfExecLogPath string
}
func NewModuleManager(fs filesystem.Filesystem) ModuleManager {
return newModuleManager(fs)
}
func newModuleManager(fs filesystem.Filesystem) *moduleManager {
d := &discovery.Discovery{}
defaultSize := 3 * runtime.NumCPU()
wp := workerpool.New(defaultSize)
mm := &moduleManager{
modules: make([]*module, 0),
filesystem: fs,
workerPool: wp,
logger: defaultLogger,
tfDiscoFunc: d.LookPath,
tfNewExecutor: exec.NewExecutor,
}
mm.newModule = mm.defaultModuleFactory
return mm
}
func (mm *moduleManager) WorkerPoolSize() int {
return mm.workerPool.Size()
}
func (mm *moduleManager) WorkerQueueSize() int {
return mm.workerPool.WaitingQueueSize()
}
func (mm *moduleManager) defaultModuleFactory(ctx context.Context, dir string) (*module, error) {
mod := newModule(mm.filesystem, dir)
mod.SetLogger(mm.logger)
d := &discovery.Discovery{}
mod.tfDiscoFunc = d.LookPath
mod.tfNewExecutor = exec.NewExecutor
mod.tfExecPath = mm.tfExecPath
mod.tfExecTimeout = mm.tfExecTimeout
mod.tfExecLogPath = mm.tfExecLogPath
return mod, mod.discoverCaches(ctx, dir)
}
func (mm *moduleManager) SetTerraformExecPath(path string) {
mm.tfExecPath = path
}
func (mm *moduleManager) SetTerraformExecLogPath(logPath string) {
mm.tfExecLogPath = logPath
}
func (mm *moduleManager) SetTerraformExecTimeout(timeout time.Duration) {
mm.tfExecTimeout = timeout
}
func (mm *moduleManager) SetLogger(logger *log.Logger) {
mm.logger = logger
}
func (mm *moduleManager) InitAndUpdateModule(ctx context.Context, dir string) (Module, error) {
mod, err := mm.ModuleByPath(dir)
if err != nil {
return nil, fmt.Errorf("failed to get module: %+v", err)
}
if err := mod.ExecuteTerraformInit(ctx); err != nil {
return nil, fmt.Errorf("failed to init module: %+v", err)
}
m := mod.(*module)
m.discoverCaches(ctx, dir)
return mod, m.UpdateProviderSchemaCache(ctx, m.pluginLockFile)
}
func (mm *moduleManager) AddAndStartLoadingModule(ctx context.Context, dir string) (Module, error) {
dir = filepath.Clean(dir)
// TODO: Follow symlinks (requires proper test data)
if _, ok := mm.moduleByPath(dir); ok {
return nil, fmt.Errorf("module %s was already added", dir)
}
mod, err := mm.newModule(context.Background(), dir)
if err != nil {
return nil, err
}
mm.modules = append(mm.modules, mod)
if mm.syncLoading {
mm.logger.Printf("synchronously loading module %s", dir)
return mod, mod.load(ctx)
}
mm.logger.Printf("asynchronously loading module %s", dir)
mm.workerPool.Submit(func() {
mod := mod
err := mod.load(context.Background())
mod.setLoadErr(err)
})
return mod, nil
}
func (mm *moduleManager) SchemaForPath(path string) (*schema.BodySchema, error) {
candidates := mm.ModuleCandidatesByPath(path)
for _, mod := range candidates {
schema, err := mod.MergedSchema()
if err != nil {
mm.logger.Printf("failed to merge schema for %s: %s", mod.Path(), err)
continue
}
if schema != nil {
mm.logger.Printf("found schema for %s at %s", path, mod.Path())
return schema, nil
}
}
mod, err := mm.ModuleByPath(path)
if err != nil {
return nil, err
}
return mod.MergedSchema()
}
func (mm *moduleManager) moduleByPath(dir string) (*module, bool) {
for _, mod := range mm.modules {
if pathEquals(mod.Path(), dir) {
return mod, true
}
}
return nil, false
}
// ModuleCandidatesByPath finds any initialized modules
func (mm *moduleManager) ModuleCandidatesByPath(path string) Modules {
path = filepath.Clean(path)
candidates := make([]Module, 0)
// TODO: Follow symlinks (requires proper test data)
mod, foundPath := mm.moduleByPath(path)
if foundPath {
inited, _ := mod.WasInitialized()
if inited {
candidates = append(candidates, mod)
}
}
if !foundPath {
dir := trimLockFilePath(path)
mod, ok := mm.moduleByPath(dir)
if ok {
inited, _ := mod.WasInitialized()
if inited {
candidates = append(candidates, mod)
}
}
}
for _, mod := range mm.modules {
if mod.ReferencesModulePath(path) {
candidates = append(candidates, mod)
}
}
return candidates
}
func (mm *moduleManager) ListModules() Modules {
modules := make([]Module, 0)
for _, mod := range mm.modules {
modules = append(modules, mod)
}
return modules
}
func (mm *moduleManager) ModuleByPath(path string) (Module, error) {
path = filepath.Clean(path)
if mod, ok := mm.moduleByPath(path); ok {
return mod, nil
}
dir := trimLockFilePath(path)
if mod, ok := mm.moduleByPath(dir); ok {
return mod, nil
}
return nil, &ModuleNotFoundErr{path}
}
func (mm *moduleManager) IsProviderSchemaLoaded(path string) (bool, error) {
mod, err := mm.ModuleByPath(path)
if err != nil {
return false, err
}
return mod.IsProviderSchemaLoaded(), nil
}
func (mm *moduleManager) TerraformFormatterForDir(ctx context.Context, path string) (exec.Formatter, error) {
mod, err := mm.ModuleByPath(path)
if err != nil {
if IsModuleNotFound(err) {
return mm.newTerraformFormatter(ctx, path)
}
return nil, err
}
return mod.TerraformFormatter()
}
func (mm *moduleManager) newTerraformFormatter(ctx context.Context, workDir string) (exec.Formatter, error) {
tfPath := mm.tfExecPath
if tfPath == "" {
var err error
tfPath, err = mm.tfDiscoFunc()
if err != nil {
return nil, err
}
}
tf, err := mm.tfNewExecutor(workDir, tfPath)
if err != nil {
return nil, err
}
tf.SetLogger(mm.logger)
if mm.tfExecLogPath != "" {
tf.SetExecLogPath(mm.tfExecLogPath)
}
if mm.tfExecTimeout != 0 {
tf.SetTimeout(mm.tfExecTimeout)
}
version, _, err := tf.Version(ctx)
if err != nil {
return nil, err
}
mm.logger.Printf("Terraform version %s found at %s (alternative)", version, tf.GetExecPath())
return tf.Format, nil
}
func (mm *moduleManager) IsTerraformAvailable(path string) (bool, error) {
mod, err := mm.ModuleByPath(path)
if err != nil {
return false, err
}
return mod.IsTerraformAvailable(), nil
}
func (mm *moduleManager) HasTerraformDiscoveryFinished(path string) (bool, error) {
mod, err := mm.ModuleByPath(path)
if err != nil {
return false, err
}
return mod.HasTerraformDiscoveryFinished(), nil
}
func (mm *moduleManager) CancelLoading() {
for _, mod := range mm.modules {
mm.logger.Printf("cancelling loading for %s", mod.Path())
mod.CancelLoading()
mm.logger.Printf("loading cancelled for %s", mod.Path())
}
mm.workerPool.Stop()
}
// trimLockFilePath strips known lock file paths and filenames
// to get the directory path of the relevant module
func trimLockFilePath(filePath string) string {
pluginLockFileSuffixes := pluginLockFilePaths(string(os.PathSeparator))
for _, s := range pluginLockFileSuffixes {
if strings.HasSuffix(filePath, s) {
return strings.TrimSuffix(filePath, s)
}
}
moduleManifestSuffix := moduleManifestFilePath(string(os.PathSeparator))
if strings.HasSuffix(filePath, moduleManifestSuffix) {
return strings.TrimSuffix(filePath, moduleManifestSuffix)
}
return filePath
}
func (mm *moduleManager) PathsToWatch() []string {
paths := make([]string, 0)
for _, mod := range mm.modules {
ptw := mod.PathsToWatch()
if len(ptw) > 0 {
paths = append(paths, ptw...)
}
}
return paths
}
// NewModuleLoader allows adding & loading modules
// with a given context. This can be passed down to any handler
// which itself will have short-lived context
// therefore couldn't finish loading the module asynchronously
// after it responds to the client
func NewModuleLoader(ctx context.Context, mm ModuleManager) ModuleLoader {
return func(dir string) (Module, error) {
return mm.AddAndStartLoadingModule(ctx, dir)
}
}