github.com/hashicorp/terraform-plugin-sdk@v1.17.2/internal/configs/configload/loader_snapshot.go (about)

     1  package configload
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"os"
     7  	"path/filepath"
     8  	"sort"
     9  	"time"
    10  
    11  	version "github.com/hashicorp/go-version"
    12  	"github.com/hashicorp/hcl/v2"
    13  	"github.com/hashicorp/terraform-plugin-sdk/internal/configs"
    14  	"github.com/hashicorp/terraform-plugin-sdk/internal/modsdir"
    15  	"github.com/spf13/afero"
    16  )
    17  
    18  // LoadConfigWithSnapshot is a variant of LoadConfig that also simultaneously
    19  // creates an in-memory snapshot of the configuration files used, which can
    20  // be later used to create a loader that may read only from this snapshot.
    21  func (l *Loader) LoadConfigWithSnapshot(rootDir string) (*configs.Config, *Snapshot, hcl.Diagnostics) {
    22  	rootMod, diags := l.parser.LoadConfigDir(rootDir)
    23  	if rootMod == nil {
    24  		return nil, nil, diags
    25  	}
    26  
    27  	snap := &Snapshot{
    28  		Modules: map[string]*SnapshotModule{},
    29  	}
    30  	walker := l.makeModuleWalkerSnapshot(snap)
    31  	cfg, cDiags := configs.BuildConfig(rootMod, walker)
    32  	diags = append(diags, cDiags...)
    33  
    34  	addDiags := l.addModuleToSnapshot(snap, "", rootDir, "", nil)
    35  	diags = append(diags, addDiags...)
    36  
    37  	return cfg, snap, diags
    38  }
    39  
    40  // NewLoaderFromSnapshot creates a Loader that reads files only from the
    41  // given snapshot.
    42  //
    43  // A snapshot-based loader cannot install modules, so calling InstallModules
    44  // on the return value will cause a panic.
    45  //
    46  // A snapshot-based loader also has access only to configuration files. Its
    47  // underlying parser does not have access to other files in the native
    48  // filesystem, such as values files. For those, either use a normal loader
    49  // (created by NewLoader) or use the configs.Parser API directly.
    50  func NewLoaderFromSnapshot(snap *Snapshot) *Loader {
    51  	fs := snapshotFS{snap}
    52  	parser := configs.NewParser(fs)
    53  
    54  	ret := &Loader{
    55  		parser: parser,
    56  		modules: moduleMgr{
    57  			FS:         afero.Afero{Fs: fs},
    58  			CanInstall: false,
    59  			manifest:   snap.moduleManifest(),
    60  		},
    61  	}
    62  
    63  	return ret
    64  }
    65  
    66  // Snapshot is an in-memory representation of the source files from a
    67  // configuration, which can be used as an alternative configurations source
    68  // for a loader with NewLoaderFromSnapshot.
    69  //
    70  // The primary purpose of a Snapshot is to build the configuration portion
    71  // of a plan file (see ../../plans/planfile) so that it can later be reloaded
    72  // and used to recover the exact configuration that the plan was built from.
    73  type Snapshot struct {
    74  	// Modules is a map from opaque module keys (suitable for use as directory
    75  	// names on all supported operating systems) to the snapshot information
    76  	// about each module.
    77  	Modules map[string]*SnapshotModule
    78  }
    79  
    80  // SnapshotModule represents a single module within a Snapshot.
    81  type SnapshotModule struct {
    82  	// Dir is the path, relative to the root directory given when the
    83  	// snapshot was created, where the module appears in the snapshot's
    84  	// virtual filesystem.
    85  	Dir string
    86  
    87  	// Files is a map from each configuration file filename for the
    88  	// module to a raw byte representation of the source file contents.
    89  	Files map[string][]byte
    90  
    91  	// SourceAddr is the source address given for this module in configuration.
    92  	SourceAddr string `json:"Source"`
    93  
    94  	// Version is the version of the module that is installed, or nil if
    95  	// the module is installed from a source that does not support versions.
    96  	Version *version.Version `json:"-"`
    97  }
    98  
    99  // moduleManifest constructs a module manifest based on the contents of
   100  // the receiving snapshot.
   101  func (s *Snapshot) moduleManifest() modsdir.Manifest {
   102  	ret := make(modsdir.Manifest)
   103  
   104  	for k, modSnap := range s.Modules {
   105  		ret[k] = modsdir.Record{
   106  			Key:        k,
   107  			Dir:        modSnap.Dir,
   108  			SourceAddr: modSnap.SourceAddr,
   109  			Version:    modSnap.Version,
   110  		}
   111  	}
   112  
   113  	return ret
   114  }
   115  
   116  // makeModuleWalkerSnapshot creates a configs.ModuleWalker that will exhibit
   117  // the same lookup behaviors as l.moduleWalkerLoad but will additionally write
   118  // source files from the referenced modules into the given snapshot.
   119  func (l *Loader) makeModuleWalkerSnapshot(snap *Snapshot) configs.ModuleWalker {
   120  	return configs.ModuleWalkerFunc(
   121  		func(req *configs.ModuleRequest) (*configs.Module, *version.Version, hcl.Diagnostics) {
   122  			mod, v, diags := l.moduleWalkerLoad(req)
   123  			if diags.HasErrors() {
   124  				return mod, v, diags
   125  			}
   126  
   127  			key := l.modules.manifest.ModuleKey(req.Path)
   128  			record, exists := l.modules.manifest[key]
   129  
   130  			if !exists {
   131  				// Should never happen, since otherwise moduleWalkerLoader would've
   132  				// returned an error and we would've returned already.
   133  				panic(fmt.Sprintf("module %s is not present in manifest", key))
   134  			}
   135  
   136  			addDiags := l.addModuleToSnapshot(snap, key, record.Dir, record.SourceAddr, record.Version)
   137  			diags = append(diags, addDiags...)
   138  
   139  			return mod, v, diags
   140  		},
   141  	)
   142  }
   143  
   144  func (l *Loader) addModuleToSnapshot(snap *Snapshot, key string, dir string, sourceAddr string, v *version.Version) hcl.Diagnostics {
   145  	var diags hcl.Diagnostics
   146  
   147  	primaryFiles, overrideFiles, moreDiags := l.parser.ConfigDirFiles(dir)
   148  	if moreDiags.HasErrors() {
   149  		// Any diagnostics we get here should be already present
   150  		// in diags, so it's weird if we get here but we'll allow it
   151  		// and return a general error message in that case.
   152  		diags = append(diags, &hcl.Diagnostic{
   153  			Severity: hcl.DiagError,
   154  			Summary:  "Failed to read directory for module",
   155  			Detail:   fmt.Sprintf("The source directory %s could not be read", dir),
   156  		})
   157  		return diags
   158  	}
   159  
   160  	snapMod := &SnapshotModule{
   161  		Dir:        dir,
   162  		Files:      map[string][]byte{},
   163  		SourceAddr: sourceAddr,
   164  		Version:    v,
   165  	}
   166  
   167  	files := make([]string, 0, len(primaryFiles)+len(overrideFiles))
   168  	files = append(files, primaryFiles...)
   169  	files = append(files, overrideFiles...)
   170  	sources := l.Sources() // should be populated with all the files we need by now
   171  	for _, filePath := range files {
   172  		filename := filepath.Base(filePath)
   173  		src, exists := sources[filePath]
   174  		if !exists {
   175  			diags = append(diags, &hcl.Diagnostic{
   176  				Severity: hcl.DiagError,
   177  				Summary:  "Missing source file for snapshot",
   178  				Detail:   fmt.Sprintf("The source code for file %s could not be found to produce a configuration snapshot.", filePath),
   179  			})
   180  			continue
   181  		}
   182  		snapMod.Files[filepath.Clean(filename)] = src
   183  	}
   184  
   185  	snap.Modules[key] = snapMod
   186  
   187  	return diags
   188  }
   189  
   190  // snapshotFS is an implementation of afero.Fs that reads from a snapshot.
   191  //
   192  // This is not intended as a general-purpose filesystem implementation. Instead,
   193  // it just supports the minimal functionality required to support the
   194  // configuration loader and parser as an implementation detail of creating
   195  // a loader from a snapshot.
   196  type snapshotFS struct {
   197  	snap *Snapshot
   198  }
   199  
   200  var _ afero.Fs = snapshotFS{}
   201  
   202  func (fs snapshotFS) Create(name string) (afero.File, error) {
   203  	return nil, fmt.Errorf("cannot create file inside configuration snapshot")
   204  }
   205  
   206  func (fs snapshotFS) Mkdir(name string, perm os.FileMode) error {
   207  	return fmt.Errorf("cannot create directory inside configuration snapshot")
   208  }
   209  
   210  func (fs snapshotFS) MkdirAll(name string, perm os.FileMode) error {
   211  	return fmt.Errorf("cannot create directories inside configuration snapshot")
   212  }
   213  
   214  func (fs snapshotFS) Open(name string) (afero.File, error) {
   215  
   216  	// Our "filesystem" is sparsely populated only with the directories
   217  	// mentioned by modules in our snapshot, so the high-level process
   218  	// for opening a file is:
   219  	// - Find the module snapshot corresponding to the containing directory
   220  	// - Find the file within that snapshot
   221  	// - Wrap the resulting byte slice in a snapshotFile to return
   222  	//
   223  	// The other possibility handled here is if the given name is for the
   224  	// module directory itself, in which case we'll return a snapshotDir
   225  	// instead.
   226  	//
   227  	// This function doesn't try to be incredibly robust in supporting
   228  	// different permutations of paths, etc because in practice we only
   229  	// need to support the path forms that our own loader and parser will
   230  	// generate.
   231  
   232  	dir := filepath.Dir(name)
   233  	fn := filepath.Base(name)
   234  	directDir := filepath.Clean(name)
   235  
   236  	// First we'll check to see if this is an exact path for a module directory.
   237  	// We need to do this first (rather than as part of the next loop below)
   238  	// because a module in a child directory of another module can otherwise
   239  	// appear to be a file in that parent directory.
   240  	for _, candidate := range fs.snap.Modules {
   241  		modDir := filepath.Clean(candidate.Dir)
   242  		if modDir == directDir {
   243  			// We've matched the module directory itself
   244  			filenames := make([]string, 0, len(candidate.Files))
   245  			for n := range candidate.Files {
   246  				filenames = append(filenames, n)
   247  			}
   248  			sort.Strings(filenames)
   249  			return snapshotDir{
   250  				filenames: filenames,
   251  			}, nil
   252  		}
   253  	}
   254  
   255  	// If we get here then the given path isn't a module directory exactly, so
   256  	// we'll treat it as a file path and try to find a module directory it
   257  	// could be located in.
   258  	var modSnap *SnapshotModule
   259  	for _, candidate := range fs.snap.Modules {
   260  		modDir := filepath.Clean(candidate.Dir)
   261  		if modDir == dir {
   262  			modSnap = candidate
   263  			break
   264  		}
   265  	}
   266  	if modSnap == nil {
   267  		return nil, os.ErrNotExist
   268  	}
   269  
   270  	src, exists := modSnap.Files[fn]
   271  	if !exists {
   272  		return nil, os.ErrNotExist
   273  	}
   274  
   275  	return &snapshotFile{
   276  		src: src,
   277  	}, nil
   278  }
   279  
   280  func (fs snapshotFS) OpenFile(name string, flag int, perm os.FileMode) (afero.File, error) {
   281  	return fs.Open(name)
   282  }
   283  
   284  func (fs snapshotFS) Remove(name string) error {
   285  	return fmt.Errorf("cannot remove file inside configuration snapshot")
   286  }
   287  
   288  func (fs snapshotFS) RemoveAll(path string) error {
   289  	return fmt.Errorf("cannot remove files inside configuration snapshot")
   290  }
   291  
   292  func (fs snapshotFS) Rename(old, new string) error {
   293  	return fmt.Errorf("cannot rename file inside configuration snapshot")
   294  }
   295  
   296  func (fs snapshotFS) Stat(name string) (os.FileInfo, error) {
   297  	f, err := fs.Open(name)
   298  	if err != nil {
   299  		return nil, err
   300  	}
   301  	_, isDir := f.(snapshotDir)
   302  	return snapshotFileInfo{
   303  		name:  filepath.Base(name),
   304  		isDir: isDir,
   305  	}, nil
   306  }
   307  
   308  func (fs snapshotFS) Name() string {
   309  	return "ConfigSnapshotFS"
   310  }
   311  
   312  func (fs snapshotFS) Chmod(name string, mode os.FileMode) error {
   313  	return fmt.Errorf("cannot set file mode inside configuration snapshot")
   314  }
   315  
   316  func (fs snapshotFS) Chtimes(name string, atime, mtime time.Time) error {
   317  	return fmt.Errorf("cannot set file times inside configuration snapshot")
   318  }
   319  
   320  type snapshotFile struct {
   321  	snapshotFileStub
   322  	src []byte
   323  	at  int64
   324  }
   325  
   326  var _ afero.File = (*snapshotFile)(nil)
   327  
   328  func (f *snapshotFile) Read(p []byte) (n int, err error) {
   329  	if len(p) > 0 && f.at == int64(len(f.src)) {
   330  		return 0, io.EOF
   331  	}
   332  	if f.at > int64(len(f.src)) {
   333  		return 0, io.ErrUnexpectedEOF
   334  	}
   335  	if int64(len(f.src))-f.at >= int64(len(p)) {
   336  		n = len(p)
   337  	} else {
   338  		n = int(int64(len(f.src)) - f.at)
   339  	}
   340  	copy(p, f.src[f.at:f.at+int64(n)])
   341  	f.at += int64(n)
   342  	return
   343  }
   344  
   345  func (f *snapshotFile) ReadAt(p []byte, off int64) (n int, err error) {
   346  	f.at = off
   347  	return f.Read(p)
   348  }
   349  
   350  func (f *snapshotFile) Seek(offset int64, whence int) (int64, error) {
   351  	switch whence {
   352  	case 0:
   353  		f.at = offset
   354  	case 1:
   355  		f.at += offset
   356  	case 2:
   357  		f.at = int64(len(f.src)) + offset
   358  	}
   359  	return f.at, nil
   360  }
   361  
   362  type snapshotDir struct {
   363  	snapshotFileStub
   364  	filenames []string
   365  	at        int
   366  }
   367  
   368  var _ afero.File = snapshotDir{}
   369  
   370  func (f snapshotDir) Readdir(count int) ([]os.FileInfo, error) {
   371  	names, err := f.Readdirnames(count)
   372  	if err != nil {
   373  		return nil, err
   374  	}
   375  	ret := make([]os.FileInfo, len(names))
   376  	for i, name := range names {
   377  		ret[i] = snapshotFileInfo{
   378  			name:  name,
   379  			isDir: false,
   380  		}
   381  	}
   382  	return ret, nil
   383  }
   384  
   385  func (f snapshotDir) Readdirnames(count int) ([]string, error) {
   386  	var outLen int
   387  	names := f.filenames[f.at:]
   388  	if count > 0 {
   389  		if len(names) < count {
   390  			outLen = len(names)
   391  		} else {
   392  			outLen = count
   393  		}
   394  		if len(names) == 0 {
   395  			return nil, io.EOF
   396  		}
   397  	} else {
   398  		outLen = len(names)
   399  	}
   400  	f.at += outLen
   401  
   402  	return names[:outLen], nil
   403  }
   404  
   405  // snapshotFileInfo is a minimal implementation of os.FileInfo to support our
   406  // virtual filesystem from snapshots.
   407  type snapshotFileInfo struct {
   408  	name  string
   409  	isDir bool
   410  }
   411  
   412  var _ os.FileInfo = snapshotFileInfo{}
   413  
   414  func (fi snapshotFileInfo) Name() string {
   415  	return fi.name
   416  }
   417  
   418  func (fi snapshotFileInfo) Size() int64 {
   419  	// In practice, our parser and loader never call Size
   420  	return -1
   421  }
   422  
   423  func (fi snapshotFileInfo) Mode() os.FileMode {
   424  	return os.ModePerm
   425  }
   426  
   427  func (fi snapshotFileInfo) ModTime() time.Time {
   428  	return time.Now()
   429  }
   430  
   431  func (fi snapshotFileInfo) IsDir() bool {
   432  	return fi.isDir
   433  }
   434  
   435  func (fi snapshotFileInfo) Sys() interface{} {
   436  	return nil
   437  }
   438  
   439  type snapshotFileStub struct{}
   440  
   441  func (f snapshotFileStub) Close() error {
   442  	return nil
   443  }
   444  
   445  func (f snapshotFileStub) Read(p []byte) (n int, err error) {
   446  	return 0, fmt.Errorf("cannot read")
   447  }
   448  
   449  func (f snapshotFileStub) ReadAt(p []byte, off int64) (n int, err error) {
   450  	return 0, fmt.Errorf("cannot read")
   451  }
   452  
   453  func (f snapshotFileStub) Seek(offset int64, whence int) (int64, error) {
   454  	return 0, fmt.Errorf("cannot seek")
   455  }
   456  
   457  func (f snapshotFileStub) Write(p []byte) (n int, err error) {
   458  	return f.WriteAt(p, 0)
   459  }
   460  
   461  func (f snapshotFileStub) WriteAt(p []byte, off int64) (n int, err error) {
   462  	return 0, fmt.Errorf("cannot write to file in snapshot")
   463  }
   464  
   465  func (f snapshotFileStub) WriteString(s string) (n int, err error) {
   466  	return 0, fmt.Errorf("cannot write to file in snapshot")
   467  }
   468  
   469  func (f snapshotFileStub) Name() string {
   470  	// in practice, the loader and parser never use this
   471  	return "<unimplemented>"
   472  }
   473  
   474  func (f snapshotFileStub) Readdir(count int) ([]os.FileInfo, error) {
   475  	return nil, fmt.Errorf("cannot use Readdir on a file")
   476  }
   477  
   478  func (f snapshotFileStub) Readdirnames(count int) ([]string, error) {
   479  	return nil, fmt.Errorf("cannot use Readdir on a file")
   480  }
   481  
   482  func (f snapshotFileStub) Stat() (os.FileInfo, error) {
   483  	return nil, fmt.Errorf("cannot stat")
   484  }
   485  
   486  func (f snapshotFileStub) Sync() error {
   487  	return nil
   488  }
   489  
   490  func (f snapshotFileStub) Truncate(size int64) error {
   491  	return fmt.Errorf("cannot write to file in snapshot")
   492  }