Skip to content

Commit

Permalink
watcher: Detect 'terraform init' from scratch
Browse files Browse the repository at this point in the history
This is a bigger change than perhaps expected but I was not able to come up with any decent way of splitting it up.

As mentioned in one in-line comment, there is currently no reliable and efficient way of watching a directory *recursively* in Go. There are some alternative solutions, but they either involve cgo or don't actually use any "event API" of the underlying OS but repeatedly do filewalk.

Previously we watched individual manifest and lock file of a module and we can't watch for *creation* of these files in a directory which doesn't exist yet. Therefore it was decided to instead watch the relevant parent directories and add relevant nested directories on creation and/or walk the hierarchy of the newly created dir. This creates even more places from where parts of module can be (re)loaded (walker, watcher, handlers), which would be hard to accommodate in the old design.

Therefore a mechanism for queueing all module operations was created.

This allows for a naive deduplication of operations (we don't run the same operation on the same module if it's already queued) and also allows us to report progress more easily in the future.

Finally this design also allows any caller to decide whether run an operation synchronously or asynchronously. e.g. We can wait for a module to be parsed in textDocument/didChange handler.
  • Loading branch information
radeksimko committed Jan 26, 2021
1 parent 9f7101d commit 8f83b21
Show file tree
Hide file tree
Showing 69 changed files with 2,396 additions and 2,113 deletions.
16 changes: 11 additions & 5 deletions internal/cmd/completion_command.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,21 +102,27 @@ func (c *CompletionCommand) Run(args []string) int {
return 1
}

module, err := module.NewModule(context.Background(), fs, fh.Dir())
ctx := context.Background()
modMgr := module.NewSyncModuleManager(ctx, fs)

mod, err := modMgr.AddModule(fh.Dir())
if err != nil {
c.Ui.Error(fmt.Sprintf("failed to load module: %s", err.Error()))
c.Ui.Error(err.Error())
return 1
}
schema, err := module.MergedSchema()

schema, err := modMgr.SchemaForModule(fh.Dir())
if err != nil {
c.Ui.Error(fmt.Sprintf("failed to find schema: %s", err.Error()))
return 1
}
d, err := module.DecoderWithSchema(schema)

d, err := module.DecoderForModule(mod)
if err != nil {
c.Ui.Error(fmt.Sprintf("failed to find parser: %s", err.Error()))
c.Ui.Error(fmt.Sprintf("failed to find decoder: %s", err.Error()))
return 1
}
d.SetSchema(schema)

pos := fPos.Position()

Expand Down
47 changes: 26 additions & 21 deletions internal/cmd/inspect_module_command.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
ictx "github.com/hashicorp/terraform-ls/internal/context"
"github.com/hashicorp/terraform-ls/internal/filesystem"
"github.com/hashicorp/terraform-ls/internal/logging"
"github.com/hashicorp/terraform-ls/internal/terraform/datadir"
"github.com/hashicorp/terraform-ls/internal/terraform/module"
"github.com/mitchellh/cli"
)
Expand Down Expand Up @@ -84,46 +85,50 @@ func (c *InspectModuleCommand) inspect(rootPath string) error {

fs := filesystem.NewFilesystem()

modMgr := module.NewModuleManager(fs)
ctx := context.Background()
modMgr := module.NewSyncModuleManager(ctx, fs)
modMgr.SetLogger(c.logger)
walker := module.NewWalker()

walker := module.SyncWalker(fs, modMgr)
walker.SetLogger(c.logger)

ctx, cancel := ictx.WithSignalCancel(context.Background(),
c.logger, syscall.SIGINT, syscall.SIGTERM)
defer cancel()

err = walker.StartWalking(ctx, rootPath, func(ctx context.Context, dir string) error {
mod, err := modMgr.AddAndStartLoadingModule(ctx, dir)
if err != nil {
return err
}
<-mod.LoadingDone()

return nil
})
err = walker.StartWalking(ctx, rootPath)
if err != nil {
return err
}

<-walker.Done()

modules := modMgr.ListModules()
c.Ui.Output(fmt.Sprintf("%d modules found in total at %s", len(modules), rootPath))
for _, mod := range modules {
errs := &multierror.Error{}

err := mod.LoadError()
_, err = mod.TerraformVersion()
if err != nil {
var ok bool
errs, ok = err.(*multierror.Error)
if !ok {
return err
}
multierror.Append(errs, err)
}

_, err := mod.ProviderSchema()
if err != nil {
multierror.Append(errs, err)
}

_, err = mod.ModuleManifest()
if err != nil {
multierror.Append(errs, err)
}

_, err = mod.ParsedFiles()
if err != nil {
multierror.Append(errs, err)
}

errs.ErrorFormat = formatErrors

modules := formatModuleRecords(mod.Modules())
modules := formatModuleRecords(mod.ModuleCalls())
subModules := fmt.Sprintf("%d modules", len(modules))
if len(modules) > 0 {
subModules += "\n"
Expand Down Expand Up @@ -153,7 +158,7 @@ func formatErrors(errors []error) string {
return strings.TrimSpace(out)
}

func formatModuleRecords(mds []module.ModuleRecord) []string {
func formatModuleRecords(mds []datadir.ModuleRecord) []string {
out := make([]string, 0)
for _, m := range mds {
if m.IsRoot() {
Expand Down
41 changes: 7 additions & 34 deletions internal/context/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
lsp "github.com/hashicorp/terraform-ls/internal/protocol"
"github.com/hashicorp/terraform-ls/internal/settings"
"github.com/hashicorp/terraform-ls/internal/terraform/module"
"github.com/hashicorp/terraform-ls/internal/watcher"
)

type contextKey struct {
Expand All @@ -29,10 +28,8 @@ var (
ctxTfExecTimeout = &contextKey{"terraform execution timeout"}
ctxWatcher = &contextKey{"watcher"}
ctxModuleMngr = &contextKey{"module manager"}
ctxTfFormatterFinder = &contextKey{"terraform formatter finder"}
ctxModuleCaFi = &contextKey{"module candidate finder"}
ctxModuleFinder = &contextKey{"module finder"}
ctxModuleWalker = &contextKey{"module walker"}
ctxModuleLoader = &contextKey{"module loader"}
ctxRootDir = &contextKey{"root directory"}
ctxCommandPrefix = &contextKey{"command prefix"}
ctxDiags = &contextKey{"diagnostics"}
Expand Down Expand Up @@ -103,12 +100,12 @@ func TerraformExecTimeout(ctx context.Context) (time.Duration, bool) {
return path, ok
}

func WithWatcher(ctx context.Context, w watcher.Watcher) context.Context {
func WithWatcher(ctx context.Context, w module.Watcher) context.Context {
return context.WithValue(ctx, ctxWatcher, w)
}

func Watcher(ctx context.Context) (watcher.Watcher, error) {
w, ok := ctx.Value(ctxWatcher).(watcher.Watcher)
func Watcher(ctx context.Context) (module.Watcher, error) {
w, ok := ctx.Value(ctxWatcher).(module.Watcher)
if !ok {
return nil, missingContextErr(ctxWatcher)
}
Expand All @@ -127,18 +124,6 @@ func ModuleManager(ctx context.Context) (module.ModuleManager, error) {
return wm, nil
}

func WithTerraformFormatterFinder(ctx context.Context, tef module.TerraformFormatterFinder) context.Context {
return context.WithValue(ctx, ctxTfFormatterFinder, tef)
}

func TerraformFormatterFinder(ctx context.Context) (module.TerraformFormatterFinder, error) {
pf, ok := ctx.Value(ctxTfFormatterFinder).(module.TerraformFormatterFinder)
if !ok {
return nil, missingContextErr(ctxTfFormatterFinder)
}
return pf, nil
}

func WithTerraformExecPath(ctx context.Context, path string) context.Context {
return context.WithValue(ctx, ctxTfExecPath, path)
}
Expand All @@ -149,13 +134,13 @@ func TerraformExecPath(ctx context.Context) (string, bool) {
}

func WithModuleFinder(ctx context.Context, mf module.ModuleFinder) context.Context {
return context.WithValue(ctx, ctxModuleCaFi, mf)
return context.WithValue(ctx, ctxModuleFinder, mf)
}

func ModuleFinder(ctx context.Context) (module.ModuleFinder, error) {
cf, ok := ctx.Value(ctxModuleCaFi).(module.ModuleFinder)
cf, ok := ctx.Value(ctxModuleFinder).(module.ModuleFinder)
if !ok {
return nil, missingContextErr(ctxModuleCaFi)
return nil, missingContextErr(ctxModuleFinder)
}
return cf, nil
}
Expand Down Expand Up @@ -216,18 +201,6 @@ func ModuleWalker(ctx context.Context) (*module.Walker, error) {
return w, nil
}

func WithModuleLoader(ctx context.Context, ml module.ModuleLoader) context.Context {
return context.WithValue(ctx, ctxModuleLoader, ml)
}

func ModuleLoader(ctx context.Context) (module.ModuleLoader, error) {
w, ok := ctx.Value(ctxModuleLoader).(module.ModuleLoader)
if !ok {
return nil, missingContextErr(ctxModuleLoader)
}
return w, nil
}

func WithDiagnostics(ctx context.Context, diags *diagnostics.Notifier) context.Context {
return context.WithValue(ctx, ctxDiags, diags)
}
Expand Down
19 changes: 16 additions & 3 deletions internal/filesystem/filesystem.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package filesystem

import (
"bytes"
"fmt"
"io/ioutil"
"log"
"os"
Expand Down Expand Up @@ -36,6 +37,18 @@ func (fs *fsystem) SetLogger(logger *log.Logger) {
}

func (fs *fsystem) CreateDocument(dh DocumentHandler, text []byte) error {
_, err := fs.memFs.Stat(dh.Dir())
if err != nil {
if os.IsNotExist(err) {
err := fs.memFs.MkdirAll(dh.Dir(), 0755)
if err != nil {
return fmt.Errorf("failed to create parent dir: %w", err)
}
} else {
return err
}
}

f, err := fs.memFs.Create(dh.FullPath())
if err != nil {
return err
Expand Down Expand Up @@ -196,11 +209,11 @@ func (fs *fsystem) ReadFile(name string) ([]byte, error) {
func (fs *fsystem) ReadDir(name string) ([]os.FileInfo, error) {
memList, err := afero.ReadDir(fs.memFs, name)
if err != nil && !os.IsNotExist(err) {
return nil, err
return nil, fmt.Errorf("memory FS: %w", err)
}
osList, err := afero.ReadDir(fs.osFs, name)
if err != nil {
return nil, err
if err != nil && !os.IsNotExist(err) {
return nil, fmt.Errorf("OS FS: %w", err)
}

list := memList
Expand Down
23 changes: 23 additions & 0 deletions internal/filesystem/filesystem_metadata.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package filesystem

import (
"path/filepath"

"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/terraform-ls/internal/uri"
)

func (fs *fsystem) markDocumentAsOpen(dh DocumentHandler) error {
Expand All @@ -16,6 +19,26 @@ func (fs *fsystem) markDocumentAsOpen(dh DocumentHandler) error {
return nil
}

func (fs *fsystem) HasOpenFiles(dirPath string) (bool, error) {
files, err := fs.ReadDir(dirPath)
if err != nil {
return false, err
}

fs.docMetaMu.RLock()
defer fs.docMetaMu.RUnlock()

for _, fi := range files {
u := uri.FromPath(filepath.Join(dirPath, fi.Name()))
dm, ok := fs.docMeta[u]
if ok && dm.IsOpen() {
return true, nil
}
}

return false, nil
}

func (fs *fsystem) createDocumentMetadata(dh DocumentHandler, text []byte) error {
if fs.documentMetadataExists(dh) {
return &MetadataAlreadyExistsErr{dh}
Expand Down
Loading

0 comments on commit 8f83b21

Please sign in to comment.