11 version "github.com/hashicorp/go-version"
12 "github.com/hashicorp/hcl2/hcl"
13 "github.com/hashicorp/terraform/configs"
14 "github.com/hashicorp/terraform/internal/modsdir"
15 "github.com/spf13/afero"
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)
24 return nil, nil, diags
28 Modules: map[string]*SnapshotModule{},
30 walker := l.makeModuleWalkerSnapshot(snap)
31 cfg, cDiags := configs.BuildConfig(rootMod, walker)
32 diags = append(diags, cDiags...)
34 addDiags := l.addModuleToSnapshot(snap, "", rootDir, "", nil)
35 diags = append(diags, addDiags...)
37 return cfg, snap, diags
40 // NewLoaderFromSnapshot creates a Loader that reads files only from the
43 // A snapshot-based loader cannot install modules, so calling InstallModules
44 // on the return value will cause a panic.
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)
57 FS: afero.Afero{Fs: fs},
59 manifest: snap.moduleManifest(),
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.
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
77 Modules map[string]*SnapshotModule
80 // NewEmptySnapshot constructs and returns a snapshot containing only an empty
81 // root module. This is not useful for anything except placeholders in tests.
82 func NewEmptySnapshot() *Snapshot {
84 Modules: map[string]*SnapshotModule{
86 Files: map[string][]byte{},
92 // SnapshotModule represents a single module within a Snapshot.
93 type SnapshotModule struct {
94 // Dir is the path, relative to the root directory given when the
95 // snapshot was created, where the module appears in the snapshot's
96 // virtual filesystem.
99 // Files is a map from each configuration file filename for the
100 // module to a raw byte representation of the source file contents.
101 Files map[string][]byte
103 // SourceAddr is the source address given for this module in configuration.
104 SourceAddr string `json:"Source"`
106 // Version is the version of the module that is installed, or nil if
107 // the module is installed from a source that does not support versions.
108 Version *version.Version `json:"-"`
111 // moduleManifest constructs a module manifest based on the contents of
112 // the receiving snapshot.
113 func (s *Snapshot) moduleManifest() modsdir.Manifest {
114 ret := make(modsdir.Manifest)
116 for k, modSnap := range s.Modules {
117 ret[k] = modsdir.Record{
120 SourceAddr: modSnap.SourceAddr,
121 Version: modSnap.Version,
128 // makeModuleWalkerSnapshot creates a configs.ModuleWalker that will exhibit
129 // the same lookup behaviors as l.moduleWalkerLoad but will additionally write
130 // source files from the referenced modules into the given snapshot.
131 func (l *Loader) makeModuleWalkerSnapshot(snap *Snapshot) configs.ModuleWalker {
132 return configs.ModuleWalkerFunc(
133 func(req *configs.ModuleRequest) (*configs.Module, *version.Version, hcl.Diagnostics) {
134 mod, v, diags := l.moduleWalkerLoad(req)
135 if diags.HasErrors() {
139 key := l.modules.manifest.ModuleKey(req.Path)
140 record, exists := l.modules.manifest[key]
143 // Should never happen, since otherwise moduleWalkerLoader would've
144 // returned an error and we would've returned already.
145 panic(fmt.Sprintf("module %s is not present in manifest", key))
148 addDiags := l.addModuleToSnapshot(snap, key, record.Dir, record.SourceAddr, record.Version)
149 diags = append(diags, addDiags...)
156 func (l *Loader) addModuleToSnapshot(snap *Snapshot, key string, dir string, sourceAddr string, v *version.Version) hcl.Diagnostics {
157 var diags hcl.Diagnostics
159 primaryFiles, overrideFiles, moreDiags := l.parser.ConfigDirFiles(dir)
160 if moreDiags.HasErrors() {
161 // Any diagnostics we get here should be already present
162 // in diags, so it's weird if we get here but we'll allow it
163 // and return a general error message in that case.
164 diags = append(diags, &hcl.Diagnostic{
165 Severity: hcl.DiagError,
166 Summary: "Failed to read directory for module",
167 Detail: fmt.Sprintf("The source directory %s could not be read", dir),
172 snapMod := &SnapshotModule{
174 Files: map[string][]byte{},
175 SourceAddr: sourceAddr,
179 files := make([]string, 0, len(primaryFiles)+len(overrideFiles))
180 files = append(files, primaryFiles...)
181 files = append(files, overrideFiles...)
182 sources := l.Sources() // should be populated with all the files we need by now
183 for _, filePath := range files {
184 filename := filepath.Base(filePath)
185 src, exists := sources[filePath]
187 diags = append(diags, &hcl.Diagnostic{
188 Severity: hcl.DiagError,
189 Summary: "Missing source file for snapshot",
190 Detail: fmt.Sprintf("The source code for file %s could not be found to produce a configuration snapshot.", filePath),
194 snapMod.Files[filepath.Clean(filename)] = src
197 snap.Modules[key] = snapMod
202 // snapshotFS is an implementation of afero.Fs that reads from a snapshot.
204 // This is not intended as a general-purpose filesystem implementation. Instead,
205 // it just supports the minimal functionality required to support the
206 // configuration loader and parser as an implementation detail of creating
207 // a loader from a snapshot.
208 type snapshotFS struct {
212 var _ afero.Fs = snapshotFS{}
214 func (fs snapshotFS) Create(name string) (afero.File, error) {
215 return nil, fmt.Errorf("cannot create file inside configuration snapshot")
218 func (fs snapshotFS) Mkdir(name string, perm os.FileMode) error {
219 return fmt.Errorf("cannot create directory inside configuration snapshot")
222 func (fs snapshotFS) MkdirAll(name string, perm os.FileMode) error {
223 return fmt.Errorf("cannot create directories inside configuration snapshot")
226 func (fs snapshotFS) Open(name string) (afero.File, error) {
228 // Our "filesystem" is sparsely populated only with the directories
229 // mentioned by modules in our snapshot, so the high-level process
230 // for opening a file is:
231 // - Find the module snapshot corresponding to the containing directory
232 // - Find the file within that snapshot
233 // - Wrap the resulting byte slice in a snapshotFile to return
235 // The other possibility handled here is if the given name is for the
236 // module directory itself, in which case we'll return a snapshotDir
239 // This function doesn't try to be incredibly robust in supporting
240 // different permutations of paths, etc because in practice we only
241 // need to support the path forms that our own loader and parser will
244 dir := filepath.Dir(name)
245 fn := filepath.Base(name)
246 directDir := filepath.Clean(name)
248 // First we'll check to see if this is an exact path for a module directory.
249 // We need to do this first (rather than as part of the next loop below)
250 // because a module in a child directory of another module can otherwise
251 // appear to be a file in that parent directory.
252 for _, candidate := range fs.snap.Modules {
253 modDir := filepath.Clean(candidate.Dir)
254 if modDir == directDir {
255 // We've matched the module directory itself
256 filenames := make([]string, 0, len(candidate.Files))
257 for n := range candidate.Files {
258 filenames = append(filenames, n)
260 sort.Strings(filenames)
262 filenames: filenames,
267 // If we get here then the given path isn't a module directory exactly, so
268 // we'll treat it as a file path and try to find a module directory it
269 // could be located in.
270 var modSnap *SnapshotModule
271 for _, candidate := range fs.snap.Modules {
272 modDir := filepath.Clean(candidate.Dir)
279 return nil, os.ErrNotExist
282 src, exists := modSnap.Files[fn]
284 return nil, os.ErrNotExist
287 return &snapshotFile{
292 func (fs snapshotFS) OpenFile(name string, flag int, perm os.FileMode) (afero.File, error) {
296 func (fs snapshotFS) Remove(name string) error {
297 return fmt.Errorf("cannot remove file inside configuration snapshot")
300 func (fs snapshotFS) RemoveAll(path string) error {
301 return fmt.Errorf("cannot remove files inside configuration snapshot")
304 func (fs snapshotFS) Rename(old, new string) error {
305 return fmt.Errorf("cannot rename file inside configuration snapshot")
308 func (fs snapshotFS) Stat(name string) (os.FileInfo, error) {
309 f, err := fs.Open(name)
313 _, isDir := f.(snapshotDir)
314 return snapshotFileInfo{
315 name: filepath.Base(name),
320 func (fs snapshotFS) Name() string {
321 return "ConfigSnapshotFS"
324 func (fs snapshotFS) Chmod(name string, mode os.FileMode) error {
325 return fmt.Errorf("cannot set file mode inside configuration snapshot")
328 func (fs snapshotFS) Chtimes(name string, atime, mtime time.Time) error {
329 return fmt.Errorf("cannot set file times inside configuration snapshot")
332 type snapshotFile struct {
338 var _ afero.File = (*snapshotFile)(nil)
340 func (f *snapshotFile) Read(p []byte) (n int, err error) {
341 if len(p) > 0 && f.at == int64(len(f.src)) {
344 if f.at > int64(len(f.src)) {
345 return 0, io.ErrUnexpectedEOF
347 if int64(len(f.src))-f.at >= int64(len(p)) {
350 n = int(int64(len(f.src)) - f.at)
352 copy(p, f.src[f.at:f.at+int64(n)])
357 func (f *snapshotFile) ReadAt(p []byte, off int64) (n int, err error) {
362 func (f *snapshotFile) Seek(offset int64, whence int) (int64, error) {
369 f.at = int64(len(f.src)) + offset
374 type snapshotDir struct {
380 var _ afero.File = snapshotDir{}
382 func (f snapshotDir) Readdir(count int) ([]os.FileInfo, error) {
383 names, err := f.Readdirnames(count)
387 ret := make([]os.FileInfo, len(names))
388 for i, name := range names {
389 ret[i] = snapshotFileInfo{
397 func (f snapshotDir) Readdirnames(count int) ([]string, error) {
399 names := f.filenames[f.at:]
401 if len(names) < count {
414 return names[:outLen], nil
417 // snapshotFileInfo is a minimal implementation of os.FileInfo to support our
418 // virtual filesystem from snapshots.
419 type snapshotFileInfo struct {
424 var _ os.FileInfo = snapshotFileInfo{}
426 func (fi snapshotFileInfo) Name() string {
430 func (fi snapshotFileInfo) Size() int64 {
431 // In practice, our parser and loader never call Size
435 func (fi snapshotFileInfo) Mode() os.FileMode {
439 func (fi snapshotFileInfo) ModTime() time.Time {
443 func (fi snapshotFileInfo) IsDir() bool {
447 func (fi snapshotFileInfo) Sys() interface{} {
451 type snapshotFileStub struct{}
453 func (f snapshotFileStub) Close() error {
457 func (f snapshotFileStub) Read(p []byte) (n int, err error) {
458 return 0, fmt.Errorf("cannot read")
461 func (f snapshotFileStub) ReadAt(p []byte, off int64) (n int, err error) {
462 return 0, fmt.Errorf("cannot read")
465 func (f snapshotFileStub) Seek(offset int64, whence int) (int64, error) {
466 return 0, fmt.Errorf("cannot seek")
469 func (f snapshotFileStub) Write(p []byte) (n int, err error) {
470 return f.WriteAt(p, 0)
473 func (f snapshotFileStub) WriteAt(p []byte, off int64) (n int, err error) {
474 return 0, fmt.Errorf("cannot write to file in snapshot")
477 func (f snapshotFileStub) WriteString(s string) (n int, err error) {
478 return 0, fmt.Errorf("cannot write to file in snapshot")
481 func (f snapshotFileStub) Name() string {
482 // in practice, the loader and parser never use this
483 return "<unimplemented>"
486 func (f snapshotFileStub) Readdir(count int) ([]os.FileInfo, error) {
487 return nil, fmt.Errorf("cannot use Readdir on a file")
490 func (f snapshotFileStub) Readdirnames(count int) ([]string, error) {
491 return nil, fmt.Errorf("cannot use Readdir on a file")
494 func (f snapshotFileStub) Stat() (os.FileInfo, error) {
495 return nil, fmt.Errorf("cannot stat")
498 func (f snapshotFileStub) Sync() error {
502 func (f snapshotFileStub) Truncate(size int64) error {
503 return fmt.Errorf("cannot write to file in snapshot")