github.com/Pankov404/juju@v0.0.0-20150703034450-be266991dceb/provider/ec2/config_test.go (about)

     1  // Copyright 2011, 2012, 2013 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package ec2
     5  
     6  // TODO: Clean this up so it matches environs/openstack/config_test.go.
     7  
     8  import (
     9  	"io/ioutil"
    10  	"os"
    11  	"path/filepath"
    12  	"strings"
    13  
    14  	jc "github.com/juju/testing/checkers"
    15  	"github.com/juju/utils"
    16  	"gopkg.in/amz.v3/aws"
    17  	gc "gopkg.in/check.v1"
    18  
    19  	"github.com/juju/juju/environs"
    20  	"github.com/juju/juju/environs/config"
    21  	envtesting "github.com/juju/juju/environs/testing"
    22  	"github.com/juju/juju/testing"
    23  )
    24  
    25  // Use local suite since this file lives in the ec2 package
    26  // for testing internals.
    27  type ConfigSuite struct {
    28  	testing.BaseSuite
    29  	savedHome, savedAccessKey, savedSecretKey string
    30  }
    31  
    32  var _ = gc.Suite(&ConfigSuite{})
    33  
    34  var configTestRegion = aws.Region{
    35  	Name:        "configtest",
    36  	EC2Endpoint: "testregion.nowhere:1234",
    37  }
    38  
    39  var testAuth = aws.Auth{"gopher", "long teeth"}
    40  
    41  // configTest specifies a config parsing test, checking that env when
    42  // parsed as the ec2 section of a config file matches baseConfigResult
    43  // when mutated by the mutate function, or that the parse matches the
    44  // given error.
    45  type configTest struct {
    46  	config             map[string]interface{}
    47  	change             map[string]interface{}
    48  	expect             map[string]interface{}
    49  	region             string
    50  	cbucket            string
    51  	pbucket            string
    52  	pbucketRegion      string
    53  	accessKey          string
    54  	secretKey          string
    55  	firewallMode       string
    56  	blockStorageSource string
    57  	err                string
    58  }
    59  
    60  type attrs map[string]interface{}
    61  
    62  func (t configTest) check(c *gc.C) {
    63  	attrs := testing.FakeConfig().Merge(testing.Attrs{
    64  		"type":           "ec2",
    65  		"control-bucket": "x",
    66  	}).Merge(t.config)
    67  	cfg, err := config.New(config.NoDefaults, attrs)
    68  	c.Assert(err, jc.ErrorIsNil)
    69  	e, err := environs.New(cfg)
    70  	if t.change != nil {
    71  		c.Assert(err, jc.ErrorIsNil)
    72  
    73  		// Testing a change in configuration.
    74  		var old, changed, valid *config.Config
    75  		ec2env := e.(*environ)
    76  		old = ec2env.ecfg().Config
    77  		changed, err = old.Apply(t.change)
    78  		c.Assert(err, jc.ErrorIsNil)
    79  
    80  		// Keep err for validation below.
    81  		valid, err = providerInstance.Validate(changed, old)
    82  		if err == nil {
    83  			err = ec2env.SetConfig(valid)
    84  		}
    85  	}
    86  	if t.err != "" {
    87  		c.Check(err, gc.ErrorMatches, t.err)
    88  		return
    89  	}
    90  	c.Assert(err, jc.ErrorIsNil)
    91  
    92  	ecfg := e.(*environ).ecfg()
    93  	c.Assert(ecfg.Name(), gc.Equals, "testenv")
    94  	c.Assert(ecfg.controlBucket(), gc.Equals, "x")
    95  	if t.region != "" {
    96  		c.Assert(ecfg.region(), gc.Equals, t.region)
    97  	}
    98  	if t.accessKey != "" {
    99  		c.Assert(ecfg.accessKey(), gc.Equals, t.accessKey)
   100  		c.Assert(ecfg.secretKey(), gc.Equals, t.secretKey)
   101  		expected := map[string]string{
   102  			"access-key": t.accessKey,
   103  			"secret-key": t.secretKey,
   104  		}
   105  		c.Assert(err, jc.ErrorIsNil)
   106  		actual, err := e.Provider().SecretAttrs(ecfg.Config)
   107  		c.Assert(err, jc.ErrorIsNil)
   108  		c.Assert(expected, gc.DeepEquals, actual)
   109  	} else {
   110  		c.Assert(ecfg.accessKey(), gc.DeepEquals, testAuth.AccessKey)
   111  		c.Assert(ecfg.secretKey(), gc.DeepEquals, testAuth.SecretKey)
   112  	}
   113  	if t.firewallMode != "" {
   114  		c.Assert(ecfg.FirewallMode(), gc.Equals, t.firewallMode)
   115  	}
   116  	for name, expect := range t.expect {
   117  		actual, found := ecfg.UnknownAttrs()[name]
   118  		c.Check(found, jc.IsTrue)
   119  		c.Check(actual, gc.Equals, expect)
   120  	}
   121  
   122  	// check storage bucket is configured correctly
   123  	env := e.(*environ)
   124  	c.Assert(env.Storage().(*ec2storage).bucket.Region.Name, gc.Equals, ecfg.region())
   125  }
   126  
   127  var configTests = []configTest{
   128  	{
   129  		config: attrs{},
   130  	}, {
   131  		// check that region defaults to us-east-1
   132  		config: attrs{},
   133  		region: "us-east-1",
   134  	}, {
   135  		config: attrs{
   136  			"region": "eu-west-1",
   137  		},
   138  		region: "eu-west-1",
   139  	}, {
   140  		config: attrs{
   141  			"region": "unknown",
   142  		},
   143  		err: ".*invalid region name.*",
   144  	}, {
   145  		config: attrs{
   146  			"region": "configtest",
   147  		},
   148  		region: "configtest",
   149  	}, {
   150  		config: attrs{
   151  			"region": "configtest",
   152  		},
   153  		change: attrs{
   154  			"region": "us-east-1",
   155  		},
   156  		err: `.*cannot change region from "configtest" to "us-east-1"`,
   157  	}, {
   158  		config: attrs{
   159  			"region": 666,
   160  		},
   161  		err: `.*expected string, got int\(666\)`,
   162  	}, {
   163  		config: attrs{
   164  			"access-key": 666,
   165  		},
   166  		err: `.*expected string, got int\(666\)`,
   167  	}, {
   168  		config: attrs{
   169  			"secret-key": 666,
   170  		},
   171  		err: `.*expected string, got int\(666\)`,
   172  	}, {
   173  		config: attrs{
   174  			"control-bucket": 666,
   175  		},
   176  		err: `.*expected string, got int\(666\)`,
   177  	}, {
   178  		change: attrs{
   179  			"control-bucket": "new-x",
   180  		},
   181  		err: `.*cannot change control-bucket from "x" to "new-x"`,
   182  	}, {
   183  		config: attrs{
   184  			"access-key": "jujuer",
   185  			"secret-key": "open sesame",
   186  		},
   187  		accessKey: "jujuer",
   188  		secretKey: "open sesame",
   189  	}, {
   190  		config: attrs{
   191  			"access-key": "jujuer",
   192  		},
   193  		err: ".*environment has no access-key or secret-key",
   194  	}, {
   195  		config: attrs{
   196  			"secret-key": "badness",
   197  		},
   198  		err: ".*environment has no access-key or secret-key",
   199  	}, {
   200  		config: attrs{
   201  			"admin-secret": "Futumpsh",
   202  		},
   203  	}, {
   204  		config:       attrs{},
   205  		firewallMode: config.FwInstance,
   206  	}, {
   207  		config:             attrs{},
   208  		blockStorageSource: "ebs",
   209  	}, {
   210  		config: attrs{
   211  			"default-block-storage-source": "ebs-fast",
   212  		},
   213  		blockStorageSource: "ebs-fast",
   214  	}, {
   215  		config: attrs{
   216  			"firewall-mode": "instance",
   217  		},
   218  		firewallMode: config.FwInstance,
   219  	}, {
   220  		config: attrs{
   221  			"firewall-mode": "global",
   222  		},
   223  		firewallMode: config.FwGlobal,
   224  	}, {
   225  		config: attrs{
   226  			"firewall-mode": "none",
   227  		},
   228  		firewallMode: config.FwNone,
   229  	}, {
   230  		config: attrs{
   231  			"ssl-hostname-verification": false,
   232  		},
   233  		err: ".*disabling ssh-hostname-verification is not supported",
   234  	}, {
   235  		config: attrs{
   236  			"future": "hammerstein",
   237  		},
   238  		expect: attrs{
   239  			"future": "hammerstein",
   240  		},
   241  	}, {
   242  		change: attrs{
   243  			"future": "hammerstein",
   244  		},
   245  		expect: attrs{
   246  			"future": "hammerstein",
   247  		},
   248  	},
   249  }
   250  
   251  func indent(s string, with string) string {
   252  	var r string
   253  	lines := strings.Split(s, "\n")
   254  	for _, l := range lines {
   255  		r += with + l + "\n"
   256  	}
   257  	return r
   258  }
   259  
   260  func (s *ConfigSuite) SetUpTest(c *gc.C) {
   261  	s.BaseSuite.SetUpTest(c)
   262  	s.savedHome = utils.Home()
   263  	s.savedAccessKey = os.Getenv("AWS_ACCESS_KEY_ID")
   264  	s.savedSecretKey = os.Getenv("AWS_SECRET_ACCESS_KEY")
   265  
   266  	home := c.MkDir()
   267  	sshDir := filepath.Join(home, ".ssh")
   268  	err := os.Mkdir(sshDir, 0777)
   269  	c.Assert(err, jc.ErrorIsNil)
   270  	err = ioutil.WriteFile(filepath.Join(sshDir, "id_rsa.pub"), []byte("sshkey\n"), 0666)
   271  	c.Assert(err, jc.ErrorIsNil)
   272  
   273  	utils.SetHome(home)
   274  	os.Setenv("AWS_ACCESS_KEY_ID", testAuth.AccessKey)
   275  	os.Setenv("AWS_SECRET_ACCESS_KEY", testAuth.SecretKey)
   276  	aws.Regions["configtest"] = configTestRegion
   277  }
   278  
   279  func (s *ConfigSuite) TearDownTest(c *gc.C) {
   280  	utils.SetHome(s.savedHome)
   281  	os.Setenv("AWS_ACCESS_KEY_ID", s.savedAccessKey)
   282  	os.Setenv("AWS_SECRET_ACCESS_KEY", s.savedSecretKey)
   283  	delete(aws.Regions, "configtest")
   284  	s.BaseSuite.TearDownTest(c)
   285  }
   286  
   287  func (s *ConfigSuite) TestConfig(c *gc.C) {
   288  	for i, t := range configTests {
   289  		c.Logf("test %d: %v", i, t.config)
   290  		t.check(c)
   291  	}
   292  }
   293  
   294  func (s *ConfigSuite) TestMissingAuth(c *gc.C) {
   295  	os.Setenv("AWS_ACCESS_KEY_ID", "")
   296  	os.Setenv("AWS_SECRET_ACCESS_KEY", "")
   297  	// Since r37 goamz uses these as fallbacks, so unset them too.
   298  	os.Setenv("EC2_ACCESS_KEY", "")
   299  	os.Setenv("EC2_SECRET_KEY", "")
   300  	test := configTests[0]
   301  	test.err = ".*environment has no access-key or secret-key"
   302  	test.check(c)
   303  }
   304  
   305  func (s *ConfigSuite) TestPrepareForCreateInsertsUniqueControlBucket(c *gc.C) {
   306  	s.PatchValue(&verifyCredentials, func(*environ) error { return nil })
   307  	attrs := testing.FakeConfig().Merge(testing.Attrs{
   308  		"type": "ec2",
   309  	})
   310  	cfg, err := config.New(config.NoDefaults, attrs)
   311  	c.Assert(err, jc.ErrorIsNil)
   312  
   313  	cfg1, err := providerInstance.PrepareForCreateEnvironment(cfg)
   314  	c.Assert(err, jc.ErrorIsNil)
   315  
   316  	bucket1 := cfg1.UnknownAttrs()["control-bucket"]
   317  	c.Assert(bucket1, gc.Matches, "[a-f0-9]{32}")
   318  
   319  	cfg2, err := providerInstance.PrepareForCreateEnvironment(cfg)
   320  	c.Assert(err, jc.ErrorIsNil)
   321  	bucket2 := cfg2.UnknownAttrs()["control-bucket"]
   322  	c.Assert(bucket2, gc.Matches, "[a-f0-9]{32}")
   323  
   324  	c.Assert(bucket1, gc.Not(gc.Equals), bucket2)
   325  }
   326  
   327  func (s *ConfigSuite) TestPrepareInsertsUniqueControlBucket(c *gc.C) {
   328  	s.PatchValue(&verifyCredentials, func(*environ) error { return nil })
   329  	attrs := testing.FakeConfig().Merge(testing.Attrs{
   330  		"type": "ec2",
   331  	})
   332  	cfg, err := config.New(config.NoDefaults, attrs)
   333  	c.Assert(err, jc.ErrorIsNil)
   334  
   335  	ctx := envtesting.BootstrapContext(c)
   336  	env0, err := providerInstance.PrepareForBootstrap(ctx, cfg)
   337  	c.Assert(err, jc.ErrorIsNil)
   338  	bucket0 := env0.(*environ).ecfg().controlBucket()
   339  	c.Assert(bucket0, gc.Matches, "[a-f0-9]{32}")
   340  
   341  	env1, err := providerInstance.PrepareForBootstrap(ctx, cfg)
   342  	c.Assert(err, jc.ErrorIsNil)
   343  	bucket1 := env1.(*environ).ecfg().controlBucket()
   344  	c.Assert(bucket1, gc.Matches, "[a-f0-9]{32}")
   345  
   346  	c.Assert(bucket1, gc.Not(gc.Equals), bucket0)
   347  }
   348  
   349  func (s *ConfigSuite) TestPrepareDoesNotTouchExistingControlBucket(c *gc.C) {
   350  	s.PatchValue(&verifyCredentials, func(*environ) error { return nil })
   351  	attrs := testing.FakeConfig().Merge(testing.Attrs{
   352  		"type":           "ec2",
   353  		"control-bucket": "burblefoo",
   354  	})
   355  	cfg, err := config.New(config.NoDefaults, attrs)
   356  	c.Assert(err, jc.ErrorIsNil)
   357  
   358  	env, err := providerInstance.PrepareForBootstrap(envtesting.BootstrapContext(c), cfg)
   359  	c.Assert(err, jc.ErrorIsNil)
   360  	bucket := env.(*environ).ecfg().controlBucket()
   361  	c.Assert(bucket, gc.Equals, "burblefoo")
   362  }
   363  
   364  func (s *ConfigSuite) TestPrepareSetsDefaultBlockSource(c *gc.C) {
   365  	s.PatchValue(&verifyCredentials, func(*environ) error { return nil })
   366  	attrs := testing.FakeConfig().Merge(testing.Attrs{
   367  		"type": "ec2",
   368  	})
   369  	cfg, err := config.New(config.NoDefaults, attrs)
   370  	c.Assert(err, jc.ErrorIsNil)
   371  
   372  	env, err := providerInstance.PrepareForBootstrap(envtesting.BootstrapContext(c), cfg)
   373  	c.Assert(err, jc.ErrorIsNil)
   374  	source, ok := env.(*environ).ecfg().StorageDefaultBlockSource()
   375  	c.Assert(ok, jc.IsTrue)
   376  	c.Assert(source, gc.Equals, "ebs")
   377  }
   378  
   379  func (*ConfigSuite) TestSchema(c *gc.C) {
   380  	fields := providerInstance.Schema()
   381  	// Check that all the fields defined in environs/config
   382  	// are in the returned schema.
   383  	globalFields, err := config.Schema(nil)
   384  	c.Assert(err, gc.IsNil)
   385  	for name, field := range globalFields {
   386  		c.Check(fields[name], jc.DeepEquals, field)
   387  	}
   388  }