2019-01-09 03:39:14 +01:00
package initwd
2018-02-15 05:13:35 +01:00
import (
2021-11-01 21:09:16 +01:00
"context"
2018-02-15 05:13:35 +01:00
"fmt"
2019-01-09 03:39:14 +01:00
"io/ioutil"
2018-02-15 05:13:35 +01:00
"log"
"os"
"path/filepath"
"sort"
"strings"
2020-10-07 18:48:25 +02:00
"github.com/hashicorp/terraform/internal/copy"
2020-03-12 01:17:30 +01:00
"github.com/hashicorp/terraform/internal/earlyconfig"
Refactoring of module source addresses and module installation
It's been a long while since we gave close attention to the codepaths for
module source address parsing and external module package installation.
Due to their age, these codepaths often diverged from our modern practices
such as representing address types in the addrs package, and encapsulating
package installation details only in a particular location.
In particular, this refactor makes source address parsing a separate step
from module installation, which therefore makes the result of that parsing
available to other Terraform subsystems which work with the configuration
representation objects.
This also presented the opportunity to better encapsulate our use of
go-getter into a new package "getmodules" (echoing "getproviders"), which
is intended to be the only part of Terraform that directly interacts with
go-getter.
This is largely just a refactor of the existing functionality into a new
code organization, but there is one notable change in behavior here: the
source address parsing now happens during configuration loading rather
than module installation, which may cause errors about invalid addresses
to be returned in different situations than before. That counts as
backward compatible because we only promise to remain compatible with
configurations that are _valid_, which means that they can be initialized,
planned, and applied without any errors. This doesn't introduce any new
error cases, and instead just makes a pre-existing error case be detected
earlier.
Our module registry client is still using its own special module address
type from registry/regsrc for now, with a small shim from the new
addrs.ModuleSourceRegistry type. Hopefully in a later commit we'll also
rework the registry client to work with the new address type, but this
commit is already big enough as it is.
2021-05-28 04:24:59 +02:00
"github.com/hashicorp/terraform/internal/getmodules"
2020-03-12 01:17:30 +01:00
2018-02-15 05:13:35 +01:00
version "github.com/hashicorp/go-version"
2019-01-09 03:39:14 +01:00
"github.com/hashicorp/terraform-config-inspect/tfconfig"
"github.com/hashicorp/terraform/internal/modsdir"
2021-05-17 18:45:36 +02:00
"github.com/hashicorp/terraform/internal/registry"
2021-05-17 19:11:06 +02:00
"github.com/hashicorp/terraform/internal/tfdiags"
2018-02-15 05:13:35 +01:00
)
const initFromModuleRootCallName = "root"
const initFromModuleRootKeyPrefix = initFromModuleRootCallName + "."
2019-01-09 03:39:14 +01:00
// DirFromModule populates the given directory (which must exist and be
2018-02-15 05:13:35 +01:00
// empty) with the contents of the module at the given source address.
//
// It does this by installing the given module and all of its descendent
// modules in a temporary root directory and then copying the installed
// files into suitable locations. As a consequence, any diagnostics it
// generates will reveal the location of this temporary directory to the
// user.
//
// This rather roundabout installation approach is taken to ensure that
// installation proceeds in a manner identical to normal module installation.
//
// If the given source address specifies a sub-directory of the given
// package then only the sub-directory and its descendents will be copied
// into the given root directory, which will cause any relative module
// references using ../ from that module to be unresolvable. Error diagnostics
// are produced in that case, to prompt the user to rewrite the source strings
// to be absolute references to the original remote module.
2021-11-01 21:09:16 +01:00
func DirFromModule ( ctx context . Context , rootDir , modulesDir , sourceAddr string , reg * registry . Client , hooks ModuleInstallHooks ) tfdiags . Diagnostics {
2019-01-09 03:39:14 +01:00
var diags tfdiags . Diagnostics
2018-02-15 05:13:35 +01:00
// The way this function works is pretty ugly, but we accept it because
// -from-module is a less important case than normal module installation
// and so it's better to keep this ugly complexity out here rather than
// adding even more complexity to the normal module installer.
// The target directory must exist but be empty.
{
2019-01-09 03:39:14 +01:00
entries , err := ioutil . ReadDir ( rootDir )
2018-02-15 05:13:35 +01:00
if err != nil {
if os . IsNotExist ( err ) {
2019-01-09 03:39:14 +01:00
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
"Target directory does not exist" ,
fmt . Sprintf ( "Cannot initialize non-existent directory %s." , rootDir ) ,
) )
2018-02-15 05:13:35 +01:00
} else {
2019-01-09 03:39:14 +01:00
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
"Failed to read target directory" ,
fmt . Sprintf ( "Error reading %s to ensure it is empty: %s." , rootDir , err ) ,
) )
2018-02-15 05:13:35 +01:00
}
return diags
}
haveEntries := false
for _ , entry := range entries {
if entry . Name ( ) == "." || entry . Name ( ) == ".." || entry . Name ( ) == ".terraform" {
continue
}
haveEntries = true
}
if haveEntries {
2019-01-09 03:39:14 +01:00
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
"Can't populate non-empty directory" ,
fmt . Sprintf ( "The target directory %s is not empty, so it cannot be initialized with the -from-module=... option." , rootDir ) ,
) )
2018-02-15 05:13:35 +01:00
return diags
}
}
2019-01-09 03:39:14 +01:00
instDir := filepath . Join ( rootDir , ".terraform/init-from-module" )
inst := NewModuleInstaller ( instDir , reg )
log . Printf ( "[DEBUG] installing modules in %s to initialize working directory from %q" , instDir , sourceAddr )
os . RemoveAll ( instDir ) // if this fails then we'll fail on MkdirAll below too
err := os . MkdirAll ( instDir , os . ModePerm )
2018-02-15 05:13:35 +01:00
if err != nil {
2019-01-09 03:39:14 +01:00
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
"Failed to create temporary directory" ,
fmt . Sprintf ( "Failed to create temporary directory %s: %s." , instDir , err ) ,
) )
2018-02-15 05:13:35 +01:00
return diags
}
2019-01-09 03:39:14 +01:00
instManifest := make ( modsdir . Manifest )
retManifest := make ( modsdir . Manifest )
2018-02-15 05:13:35 +01:00
fakeFilename := fmt . Sprintf ( "-from-module=%q" , sourceAddr )
2019-01-09 03:39:14 +01:00
fakePos := tfconfig . SourcePos {
2018-02-15 05:13:35 +01:00
Filename : fakeFilename ,
2019-01-09 03:39:14 +01:00
Line : 1 ,
2018-02-15 05:13:35 +01:00
}
2018-11-09 01:16:00 +01:00
// -from-module allows relative paths but it's different than a normal
// module address where it'd be resolved relative to the module call
// (which is synthetic, here.) To address this, we'll just patch up any
// relative paths to be absolute paths before we run, ensuring we'll
// get the right result. This also, as an important side-effect, ensures
// that the result will be "downloaded" with go-getter (copied from the
// source location), rather than just recorded as a relative path.
{
maybePath := filepath . ToSlash ( sourceAddr )
if maybePath == "." || strings . HasPrefix ( maybePath , "./" ) || strings . HasPrefix ( maybePath , "../" ) {
if wd , err := os . Getwd ( ) ; err == nil {
sourceAddr = filepath . Join ( wd , sourceAddr )
log . Printf ( "[TRACE] -from-module relative path rewritten to absolute path %s" , sourceAddr )
}
}
}
2018-02-15 05:13:35 +01:00
// Now we need to create an artificial root module that will seed our
// installation process.
2019-01-09 03:39:14 +01:00
fakeRootModule := & tfconfig . Module {
ModuleCalls : map [ string ] * tfconfig . ModuleCall {
initFromModuleRootCallName : {
Name : initFromModuleRootCallName ,
Source : sourceAddr ,
Pos : fakePos ,
2018-02-15 05:13:35 +01:00
} ,
} ,
}
// wrapHooks filters hook notifications to only include Download calls
// and to trim off the initFromModuleRootCallName prefix. We'll produce
// our own Install notifications directly below.
wrapHooks := installHooksInitDir {
Wrapped : hooks ,
}
Refactoring of module source addresses and module installation
It's been a long while since we gave close attention to the codepaths for
module source address parsing and external module package installation.
Due to their age, these codepaths often diverged from our modern practices
such as representing address types in the addrs package, and encapsulating
package installation details only in a particular location.
In particular, this refactor makes source address parsing a separate step
from module installation, which therefore makes the result of that parsing
available to other Terraform subsystems which work with the configuration
representation objects.
This also presented the opportunity to better encapsulate our use of
go-getter into a new package "getmodules" (echoing "getproviders"), which
is intended to be the only part of Terraform that directly interacts with
go-getter.
This is largely just a refactor of the existing functionality into a new
code organization, but there is one notable change in behavior here: the
source address parsing now happens during configuration loading rather
than module installation, which may cause errors about invalid addresses
to be returned in different situations than before. That counts as
backward compatible because we only promise to remain compatible with
configurations that are _valid_, which means that they can be initialized,
planned, and applied without any errors. This doesn't introduce any new
error cases, and instead just makes a pre-existing error case be detected
earlier.
Our module registry client is still using its own special module address
type from registry/regsrc for now, with a small shim from the new
addrs.ModuleSourceRegistry type. Hopefully in a later commit we'll also
rework the registry client to work with the new address type, but this
commit is already big enough as it is.
2021-05-28 04:24:59 +02:00
fetcher := getmodules . NewPackageFetcher ( )
2021-11-01 21:09:16 +01:00
_ , instDiags := inst . installDescendentModules ( ctx , fakeRootModule , rootDir , instManifest , true , wrapHooks , fetcher )
2018-02-15 05:13:35 +01:00
diags = append ( diags , instDiags ... )
if instDiags . HasErrors ( ) {
return diags
}
// If all of that succeeded then we'll now migrate what was installed
// into the final directory structure.
2019-01-09 03:39:14 +01:00
err = os . MkdirAll ( modulesDir , os . ModePerm )
2018-02-15 05:13:35 +01:00
if err != nil {
2019-01-09 03:39:14 +01:00
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
"Failed to create local modules directory" ,
fmt . Sprintf ( "Failed to create modules directory %s: %s." , modulesDir , err ) ,
) )
2018-02-15 05:13:35 +01:00
return diags
}
2019-01-09 03:39:14 +01:00
recordKeys := make ( [ ] string , 0 , len ( instManifest ) )
for k := range instManifest {
2018-02-15 05:13:35 +01:00
recordKeys = append ( recordKeys , k )
}
sort . Strings ( recordKeys )
for _ , recordKey := range recordKeys {
2019-01-09 03:39:14 +01:00
record := instManifest [ recordKey ]
2018-02-15 05:13:35 +01:00
if record . Key == initFromModuleRootCallName {
// We've found the module the user requested, which we must
// now copy into rootDir so it can be used directly.
log . Printf ( "[TRACE] copying new root module from %s to %s" , record . Dir , rootDir )
2020-10-07 18:48:25 +02:00
err := copy . CopyDir ( rootDir , record . Dir )
2018-02-15 05:13:35 +01:00
if err != nil {
2019-01-09 03:39:14 +01:00
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
"Failed to copy root module" ,
fmt . Sprintf ( "Error copying root module %q from %s to %s: %s." , sourceAddr , record . Dir , rootDir , err ) ,
) )
2018-02-15 05:13:35 +01:00
continue
}
// We'll try to load the newly-copied module here just so we can
// sniff for any module calls that ../ out of the root directory
// and must thus be rewritten to be absolute addresses again.
// For now we can't do this rewriting automatically, but we'll
// generate an error to help the user do it manually.
2019-01-09 03:39:14 +01:00
mod , _ := earlyconfig . LoadModule ( rootDir ) // ignore diagnostics since we're just doing value-add here anyway
if mod != nil {
for _ , mc := range mod . ModuleCalls {
if pathTraversesUp ( mc . Source ) {
Refactoring of module source addresses and module installation
It's been a long while since we gave close attention to the codepaths for
module source address parsing and external module package installation.
Due to their age, these codepaths often diverged from our modern practices
such as representing address types in the addrs package, and encapsulating
package installation details only in a particular location.
In particular, this refactor makes source address parsing a separate step
from module installation, which therefore makes the result of that parsing
available to other Terraform subsystems which work with the configuration
representation objects.
This also presented the opportunity to better encapsulate our use of
go-getter into a new package "getmodules" (echoing "getproviders"), which
is intended to be the only part of Terraform that directly interacts with
go-getter.
This is largely just a refactor of the existing functionality into a new
code organization, but there is one notable change in behavior here: the
source address parsing now happens during configuration loading rather
than module installation, which may cause errors about invalid addresses
to be returned in different situations than before. That counts as
backward compatible because we only promise to remain compatible with
configurations that are _valid_, which means that they can be initialized,
planned, and applied without any errors. This doesn't introduce any new
error cases, and instead just makes a pre-existing error case be detected
earlier.
Our module registry client is still using its own special module address
type from registry/regsrc for now, with a small shim from the new
addrs.ModuleSourceRegistry type. Hopefully in a later commit we'll also
rework the registry client to work with the new address type, but this
commit is already big enough as it is.
2021-05-28 04:24:59 +02:00
packageAddr , givenSubdir := getmodules . SplitPackageSubdir ( sourceAddr )
2019-01-09 03:39:14 +01:00
newSubdir := filepath . Join ( givenSubdir , mc . Source )
if pathTraversesUp ( newSubdir ) {
// This should never happen in any reasonable
// configuration since this suggests a path that
// traverses up out of the package root. We'll just
// ignore this, since we'll fail soon enough anyway
// trying to resolve this path when this module is
// loaded.
continue
}
var newAddr = packageAddr
if newSubdir != "" {
newAddr = fmt . Sprintf ( "%s//%s" , newAddr , filepath . ToSlash ( newSubdir ) )
}
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
"Root module references parent directory" ,
fmt . Sprintf ( "The requested module %q refers to a module via its parent directory. To use this as a new root module this source string must be rewritten as a remote source address, such as %q." , sourceAddr , newAddr ) ,
) )
2018-02-15 05:13:35 +01:00
continue
}
}
}
2019-01-09 03:39:14 +01:00
retManifest [ "" ] = modsdir . Record {
2018-02-15 05:13:35 +01:00
Key : "" ,
Dir : rootDir ,
}
continue
}
if ! strings . HasPrefix ( record . Key , initFromModuleRootKeyPrefix ) {
// Ignore the *real* root module, whose key is empty, since
// we're only interested in the module named "root" and its
// descendents.
continue
}
newKey := record . Key [ len ( initFromModuleRootKeyPrefix ) : ]
2019-01-09 03:39:14 +01:00
instPath := filepath . Join ( modulesDir , newKey )
tempPath := filepath . Join ( instDir , record . Key )
2018-02-15 05:13:35 +01:00
// tempPath won't be present for a module that was installed from
// a relative path, so in that case we just record the installation
// directory and assume it was already copied into place as part
// of its parent.
if _ , err := os . Stat ( tempPath ) ; err != nil {
if ! os . IsNotExist ( err ) {
2019-01-09 03:39:14 +01:00
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
"Failed to stat temporary module install directory" ,
fmt . Sprintf ( "Error from stat %s for module %s: %s." , instPath , newKey , err ) ,
) )
2018-02-15 05:13:35 +01:00
continue
}
var parentKey string
if lastDot := strings . LastIndexByte ( newKey , '.' ) ; lastDot != - 1 {
parentKey = newKey [ : lastDot ]
}
2020-06-17 19:24:56 +02:00
var parentOld modsdir . Record
// "" is the root module; all other modules get `root.` added as a prefix
if parentKey == "" {
parentOld = instManifest [ parentKey ]
} else {
parentOld = instManifest [ initFromModuleRootKeyPrefix + parentKey ]
}
2019-01-09 03:39:14 +01:00
parentNew := retManifest [ parentKey ]
2018-02-15 05:13:35 +01:00
// We need to figure out which portion of our directory is the
// parent package path and which portion is the subdirectory
// under that.
2020-06-17 19:24:56 +02:00
var baseDirRel string
baseDirRel , err = filepath . Rel ( parentOld . Dir , record . Dir )
2018-02-15 05:13:35 +01:00
if err != nil {
2020-06-17 19:24:56 +02:00
// This error may occur when installing a local module with a
// relative path, for e.g. if the source is in a directory above
// the destination ("../")
if parentOld . Dir == "." {
absDir , err := filepath . Abs ( parentOld . Dir )
if err != nil {
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
"Failed to determine module install directory" ,
fmt . Sprintf ( "Error determine relative source directory for module %s: %s." , newKey , err ) ,
) )
continue
}
baseDirRel , err = filepath . Rel ( absDir , record . Dir )
if err != nil {
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
"Failed to determine relative module source location" ,
fmt . Sprintf ( "Error determining relative source for module %s: %s." , newKey , err ) ,
) )
continue
}
} else {
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
"Failed to determine relative module source location" ,
fmt . Sprintf ( "Error determining relative source for module %s: %s." , newKey , err ) ,
) )
}
2018-02-15 05:13:35 +01:00
}
newDir := filepath . Join ( parentNew . Dir , baseDirRel )
log . Printf ( "[TRACE] relative reference for %s rewritten from %s to %s" , newKey , record . Dir , newDir )
newRecord := record // shallow copy
newRecord . Dir = newDir
newRecord . Key = newKey
2019-01-09 03:39:14 +01:00
retManifest [ newKey ] = newRecord
2018-02-15 05:13:35 +01:00
hooks . Install ( newRecord . Key , newRecord . Version , newRecord . Dir )
continue
}
2019-01-09 03:39:14 +01:00
err = os . MkdirAll ( instPath , os . ModePerm )
2018-02-15 05:13:35 +01:00
if err != nil {
2019-01-09 03:39:14 +01:00
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
"Failed to create module install directory" ,
fmt . Sprintf ( "Error creating directory %s for module %s: %s." , instPath , newKey , err ) ,
) )
2018-02-15 05:13:35 +01:00
continue
}
// We copy rather than "rename" here because renaming between directories
// can be tricky in edge-cases like network filesystems, etc.
log . Printf ( "[TRACE] copying new module %s from %s to %s" , newKey , record . Dir , instPath )
2020-10-07 18:48:25 +02:00
err := copy . CopyDir ( instPath , tempPath )
2018-02-15 05:13:35 +01:00
if err != nil {
2019-01-09 03:39:14 +01:00
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
"Failed to copy descendent module" ,
fmt . Sprintf ( "Error copying module %q from %s to %s: %s." , newKey , tempPath , rootDir , err ) ,
) )
2018-02-15 05:13:35 +01:00
continue
}
subDir , err := filepath . Rel ( tempPath , record . Dir )
if err != nil {
// Should never happen, because we constructed both directories
// from the same base and so they must have a common prefix.
panic ( err )
}
newRecord := record // shallow copy
newRecord . Dir = filepath . Join ( instPath , subDir )
newRecord . Key = newKey
2019-01-09 03:39:14 +01:00
retManifest [ newKey ] = newRecord
2018-02-15 05:13:35 +01:00
hooks . Install ( newRecord . Key , newRecord . Version , newRecord . Dir )
}
2019-01-09 03:39:14 +01:00
retManifest . WriteSnapshotToDir ( modulesDir )
2018-02-15 05:13:35 +01:00
if err != nil {
2019-01-09 03:39:14 +01:00
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
"Failed to write module manifest" ,
fmt . Sprintf ( "Error writing module manifest: %s." , err ) ,
) )
2018-02-15 05:13:35 +01:00
}
if ! diags . HasErrors ( ) {
// Try to clean up our temporary directory, but don't worry if we don't
// succeed since it shouldn't hurt anything.
2019-01-09 03:39:14 +01:00
os . RemoveAll ( instDir )
2018-02-15 05:13:35 +01:00
}
return diags
}
func pathTraversesUp ( path string ) bool {
return strings . HasPrefix ( filepath . ToSlash ( path ) , "../" )
}
// installHooksInitDir is an adapter wrapper for an InstallHooks that
// does some fakery to make downloads look like they are happening in their
// final locations, rather than in the temporary loader we use.
//
// It also suppresses "Install" calls entirely, since InitDirFromModule
// does its own installation steps after the initial installation pass
// has completed.
type installHooksInitDir struct {
2019-01-09 03:39:14 +01:00
Wrapped ModuleInstallHooks
ModuleInstallHooksImpl
2018-02-15 05:13:35 +01:00
}
func ( h installHooksInitDir ) Download ( moduleAddr , packageAddr string , version * version . Version ) {
if ! strings . HasPrefix ( moduleAddr , initFromModuleRootKeyPrefix ) {
// We won't announce the root module, since hook implementations
// don't expect to see that and the caller will usually have produced
// its own user-facing notification about what it's doing anyway.
return
}
trimAddr := moduleAddr [ len ( initFromModuleRootKeyPrefix ) : ]
h . Wrapped . Download ( trimAddr , packageAddr , version )
}