Beispiel #1
0
func (suite *environSuite) assertGetImageMetadataSources(c *gc.C, stream, officialSourcePath string) {
	// Make an env configured with the stream.
	testAttrs := maasEnvAttrs
	testAttrs = testAttrs.Merge(coretesting.Attrs{
		"maas-server": suite.testMAASObject.TestServer.URL,
	})
	if stream != "" {
		testAttrs = testAttrs.Merge(coretesting.Attrs{
			"image-stream": stream,
		})
	}
	attrs := coretesting.FakeConfig().Merge(testAttrs)
	cfg, err := config.New(config.NoDefaults, attrs)
	c.Assert(err, gc.IsNil)
	env, err := NewEnviron(cfg)
	c.Assert(err, gc.IsNil)

	// Add a dummy file to storage so we can use that to check the
	// obtained source later.
	data := makeRandomBytes(10)
	stor := NewStorage(env)
	err = stor.Put("images/filename", bytes.NewBuffer([]byte(data)), int64(len(data)))
	c.Assert(err, gc.IsNil)
	sources, err := imagemetadata.GetMetadataSources(env)
	c.Assert(err, gc.IsNil)
	c.Assert(len(sources), gc.Equals, 2)
	assertSourceContents(c, sources[0], "filename", data)
	url, err := sources[1].URL("")
	c.Assert(err, gc.IsNil)
	c.Assert(url, gc.Equals, fmt.Sprintf("http://cloud-images.ubuntu.com/%s/", officialSourcePath))
}
Beispiel #2
0
func registerAmazonTests() {
	// The following attributes hold the environment configuration
	// for running the amazon EC2 integration tests.
	//
	// This is missing keys for security reasons; set the following
	// environment variables to make the Amazon testing work:
	//  access-key: $AWS_ACCESS_KEY_ID
	//  secret-key: $AWS_SECRET_ACCESS_KEY
	attrs := coretesting.FakeConfig().Merge(map[string]interface{}{
		"name":           "sample-" + uniqueName,
		"type":           "ec2",
		"control-bucket": "juju-test-" + uniqueName,
		"admin-secret":   "for real",
		"firewall-mode":  config.FwInstance,
		"agent-version":  version.Current.Number.String(),
	})
	gc.Suite(&LiveTests{
		LiveTests: jujutest.LiveTests{
			TestConfig:     attrs,
			Attempt:        *ec2.ShortAttempt,
			CanOpenState:   true,
			HasProvisioner: true,
		},
	})
}
Beispiel #3
0
func (*environSuite) TestSetConfigAllowsEmptyFromNilAgentName(c *gc.C) {
	// bug #1256179 is that when using an older version of Juju (<1.16.2)
	// we didn't include maas-agent-name in the database, so it was 'nil'
	// in the OldConfig. However, when setting an environment, we would set
	// it to "" (because maasEnvironConfig.Validate ensures it is a 'valid'
	// string). We can't create that from NewEnviron or newConfig because
	// both of them Validate the contents. 'cmd/juju/environment
	// SetEnvironmentCommand' instead uses conn.State.EnvironConfig() which
	// just reads the content of the database into a map, so we just create
	// the map ourselves.

	// Even though we use 'nil' here, it actually stores it as "" because
	// 1.16.2 already validates the value
	baseCfg := getSimpleTestConfig(c, coretesting.Attrs{"maas-agent-name": ""})
	c.Check(baseCfg.UnknownAttrs()["maas-agent-name"], gc.Equals, "")
	env, err := maas.NewEnviron(baseCfg)
	c.Assert(err, gc.IsNil)
	provider := env.Provider()

	attrs := coretesting.FakeConfig()
	// These are attrs we need to make it a valid Config, but would usually
	// be set by other infrastructure
	attrs["type"] = "maas"
	nilCfg, err := config.New(config.NoDefaults, attrs)
	c.Assert(err, gc.IsNil)
	validatedConfig, err := provider.Validate(baseCfg, nilCfg)
	c.Assert(err, gc.IsNil)
	c.Check(validatedConfig.UnknownAttrs()["maas-agent-name"], gc.Equals, "")
	// However, you can't set it to an actual value if you haven't been using a value
	valueCfg := getSimpleTestConfig(c, coretesting.Attrs{"maas-agent-name": "agent-name"})
	_, err = provider.Validate(valueCfg, nilCfg)
	c.Check(err, gc.ErrorMatches, ".*cannot change maas-agent-name.*")
}
Beispiel #4
0
func (s *ConfigDeprecationSuite) setupEnv(c *gc.C, deprecatedKey, value string) {
	s.setupEnvCredentials()
	attrs := testing.FakeConfig().Merge(testing.Attrs{
		"name":           "testenv",
		"type":           "openstack",
		"control-bucket": "x",
		deprecatedKey:    value,
	})
	_, err := environs.NewFromAttrs(attrs)
	c.Assert(err, gc.IsNil)
}
Beispiel #5
0
func testConfig(c *gc.C, stateServer bool, vers version.Binary) *config.Config {
	testConfig, err := config.New(config.UseDefaults, coretesting.FakeConfig())
	c.Assert(err, gc.IsNil)
	testConfig, err = testConfig.Apply(map[string]interface{}{
		"type":           "sshinit_test",
		"default-series": vers.Series,
		"agent-version":  vers.Number.String(),
	})
	c.Assert(err, gc.IsNil)
	return testConfig
}
Beispiel #6
0
// newConfig creates a MAAS environment config from attributes.
func newConfig(values map[string]interface{}) (*maasEnvironConfig, error) {
	attrs := testing.FakeConfig().Merge(testing.Attrs{
		"name": "testenv",
		"type": "maas",
	}).Merge(values)
	env, err := environs.NewFromAttrs(attrs)
	if err != nil {
		return nil, err
	}
	return env.(*maasEnviron).ecfg(), nil
}
Beispiel #7
0
func dummyConfig(c *gc.C) *config.Config {
	testConfig, err := config.New(config.UseDefaults, coretesting.FakeConfig())
	c.Assert(err, gc.IsNil)
	testConfig, err = testConfig.Apply(map[string]interface{}{
		"type":          "dummy",
		"state-server":  false,
		"agent-version": version.Current.Number.String(),
	})
	c.Assert(err, gc.IsNil)
	return testConfig
}
Beispiel #8
0
func getSimpleTestConfig(c *gc.C, extraAttrs coretesting.Attrs) *config.Config {
	attrs := coretesting.FakeConfig()
	attrs["type"] = "maas"
	attrs["maas-server"] = "http://maas.testing.invalid"
	attrs["maas-oauth"] = "a:b:c"
	for k, v := range extraAttrs {
		attrs[k] = v
	}
	cfg, err := config.New(config.NoDefaults, attrs)
	c.Assert(err, gc.IsNil)
	return cfg
}
Beispiel #9
0
// To test UpdateEnvironConfig updates state, Validate returns a config
// different to both input configs
func mockValidCfg() (valid *config.Config, err error) {
	cfg, err := config.New(config.UseDefaults, coretesting.FakeConfig())
	if err != nil {
		return nil, err
	}
	valid, err = cfg.Apply(map[string]interface{}{
		"arbitrary-key": "cptn-marvel",
	})
	if err != nil {
		return nil, err
	}
	return valid, nil
}
Beispiel #10
0
func (s *ConfigSuite) TestPrepareDoesNotTouchExistingControlBucket(c *gc.C) {
	attrs := testing.FakeConfig().Merge(testing.Attrs{
		"type":           "ec2",
		"control-bucket": "burblefoo",
	})
	cfg, err := config.New(config.NoDefaults, attrs)
	c.Assert(err, gc.IsNil)

	env, err := providerInstance.Prepare(testing.Context(c), cfg)
	c.Assert(err, gc.IsNil)
	bucket := env.(*environ).ecfg().controlBucket()
	c.Assert(bucket, gc.Equals, "burblefoo")
}
Beispiel #11
0
// makeEnviron creates a functional maasEnviron for a test.
func (suite *providerSuite) makeEnviron() *maasEnviron {
	testAttrs := maasEnvAttrs
	testAttrs["maas-server"] = suite.testMAASObject.TestServer.URL
	attrs := coretesting.FakeConfig().Merge(maasEnvAttrs)
	cfg, err := config.New(config.NoDefaults, attrs)
	if err != nil {
		panic(err)
	}
	env, err := NewEnviron(cfg)
	if err != nil {
		panic(err)
	}
	return env
}
Beispiel #12
0
func validAttrs() coretesting.Attrs {
	return coretesting.FakeConfig().Merge(coretesting.Attrs{
		"type":             "joyent",
		"sdc-user":         "******",
		"sdc-key-id":       "00:11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff",
		"sdc-url":          "https://test.api.joyentcloud.com",
		"manta-user":       "******",
		"manta-key-id":     "00:11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff",
		"manta-url":        "https://test.manta.joyent.com",
		"private-key-path": "~/.ssh/provider_id_rsa",
		"algorithm":        "rsa-sha256",
		"control-dir":      "juju-test",
		"private-key":      "key",
	})
}
Beispiel #13
0
func (suite *EnvironProviderSuite) TestAgentNameShouldNotBeSetByHand(c *gc.C) {
	testJujuHome := c.MkDir()
	defer osenv.SetJujuHome(osenv.SetJujuHome(testJujuHome))
	attrs := testing.FakeConfig().Merge(testing.Attrs{
		"type":            "maas",
		"maas-oauth":      "aa:bb:cc",
		"maas-server":     "http://maas.testing.invalid/maas/",
		"maas-agent-name": "foobar",
	})
	config, err := config.New(config.NoDefaults, attrs)
	c.Assert(err, gc.IsNil)

	ctx := testing.Context(c)
	_, err = suite.makeEnviron().Provider().Prepare(ctx, config)
	c.Assert(err, gc.Equals, errAgentNameAlreadySet)
}
Beispiel #14
0
func GetFakeConfig(sdcUrl, mantaUrl string) coretesting.Attrs {
	return coretesting.FakeConfig().Merge(coretesting.Attrs{
		"name":             "joyent test environment",
		"type":             "joyent",
		"sdc-user":         testUser,
		"sdc-key-id":       testKeyFingerprint,
		"sdc-url":          sdcUrl,
		"manta-user":       testUser,
		"manta-key-id":     testKeyFingerprint,
		"manta-url":        mantaUrl,
		"private-key-path": fmt.Sprintf("~/.ssh/%s", testKeyFileName),
		"algorithm":        "rsa-sha256",
		"control-dir":      "juju-test",
		"agent-version":    version.Current.Number.String(),
	})
}
Beispiel #15
0
func (suite *EnvironProviderSuite) TestSecretAttrsReturnsSensitiveMAASAttributes(c *gc.C) {
	testJujuHome := c.MkDir()
	defer osenv.SetJujuHome(osenv.SetJujuHome(testJujuHome))
	const oauth = "aa:bb:cc"
	attrs := testing.FakeConfig().Merge(testing.Attrs{
		"type":        "maas",
		"maas-oauth":  oauth,
		"maas-server": "http://maas.testing.invalid/maas/",
	})
	config, err := config.New(config.NoDefaults, attrs)
	c.Assert(err, gc.IsNil)

	secretAttrs, err := suite.makeEnviron().Provider().SecretAttrs(config)
	c.Assert(err, gc.IsNil)

	expectedAttrs := map[string]string{"maas-oauth": oauth}
	c.Check(secretAttrs, gc.DeepEquals, expectedAttrs)
}
Beispiel #16
0
func (suite *EnvironProviderSuite) TestOpenReturnsNilInterfaceUponFailure(c *gc.C) {
	testJujuHome := c.MkDir()
	defer osenv.SetJujuHome(osenv.SetJujuHome(testJujuHome))
	const oauth = "wrongly-formatted-oauth-string"
	attrs := testing.FakeConfig().Merge(testing.Attrs{
		"type":        "maas",
		"maas-oauth":  oauth,
		"maas-server": "http://maas.testing.invalid/maas/",
	})
	config, err := config.New(config.NoDefaults, attrs)
	c.Assert(err, gc.IsNil)
	env, err := suite.makeEnviron().Provider().Open(config)
	// When Open() fails (i.e. returns a non-nil error), it returns an
	// environs.Environ interface object with a nil value and a nil
	// type.
	c.Check(env, gc.Equals, nil)
	c.Check(err, gc.ErrorMatches, ".*malformed maas-oauth.*")
}
Beispiel #17
0
func (suite *StateSuite) TestGetStateInfo(c *gc.C) {
	cert := testing.CACert
	attrs := testing.FakeConfig().Merge(testing.Attrs{
		"ca-cert":    cert,
		"state-port": 123,
		"api-port":   456,
	})
	cfg, err := config.New(config.NoDefaults, attrs)
	c.Assert(err, gc.IsNil)
	hostnames := []string{"onehost", "otherhost"}

	stateInfo, apiInfo := common.GetStateInfo(cfg, hostnames)

	c.Check(stateInfo.Addrs, gc.DeepEquals, []string{"onehost:123", "otherhost:123"})
	c.Check(string(stateInfo.CACert), gc.Equals, cert)
	c.Check(apiInfo.Addrs, gc.DeepEquals, []string{"onehost:456", "otherhost:456"})
	c.Check(string(apiInfo.CACert), gc.Equals, cert)
}
Beispiel #18
0
func (s *ConfigSuite) TestPrepareInsertsUniqueControlBucket(c *gc.C) {
	attrs := testing.FakeConfig().Merge(testing.Attrs{
		"type": "ec2",
	})
	cfg, err := config.New(config.NoDefaults, attrs)
	c.Assert(err, gc.IsNil)

	ctx := testing.Context(c)
	env0, err := providerInstance.Prepare(ctx, cfg)
	c.Assert(err, gc.IsNil)
	bucket0 := env0.(*environ).ecfg().controlBucket()
	c.Assert(bucket0, gc.Matches, "[a-f0-9]{32}")

	env1, err := providerInstance.Prepare(ctx, cfg)
	c.Assert(err, gc.IsNil)
	bucket1 := env1.(*environ).ecfg().controlBucket()
	c.Assert(bucket1, gc.Matches, "[a-f0-9]{32}")

	c.Assert(bucket1, gc.Not(gc.Equals), bucket0)
}
Beispiel #19
0
func (s *ConfigSuite) TestDeprecatedAttributesRemoved(c *gc.C) {
	s.setupEnvCredentials()
	attrs := testing.FakeConfig().Merge(testing.Attrs{
		"type":                  "openstack",
		"control-bucket":        "x",
		"default-image-id":      "id-1234",
		"default-instance-type": "big",
	})

	cfg, err := config.New(config.NoDefaults, attrs)
	c.Assert(err, gc.IsNil)
	// Keep err for validation below.
	valid, err := providerInstance.Validate(cfg, nil)
	c.Assert(err, gc.IsNil)
	// Check deprecated attributes removed.
	allAttrs := valid.AllAttrs()
	for _, attr := range []string{"default-image-id", "default-instance-type"} {
		_, ok := allAttrs[attr]
		c.Assert(ok, jc.IsFalse)
	}
}
Beispiel #20
0
func registerLiveTests() {
	attrs := coretesting.FakeConfig().Merge(map[string]interface{}{
		"name":          "sample-" + uniqueName,
		"type":          "joyent",
		"sdc-user":      os.Getenv("SDC_ACCOUNT"),
		"sdc-key-id":    os.Getenv("SDC_KEY_ID"),
		"manta-user":    os.Getenv("MANTA_USER"),
		"manta-key-id":  os.Getenv("MANTA_KEY_ID"),
		"control-dir":   "juju-test-" + uniqueName,
		"admin-secret":  "for real",
		"firewall-mode": config.FwInstance,
		"agent-version": version.Current.Number.String(),
	})
	gc.Suite(&LiveTests{
		LiveTests: jujutest.LiveTests{
			TestConfig:     attrs,
			CanOpenState:   true,
			HasProvisioner: true,
		},
	})
}
Beispiel #21
0
func makeTestConfig(cred *identity.Credentials) map[string]interface{} {
	// The following attributes hold the environment configuration
	// for running the OpenStack integration tests.
	//
	// This is missing keys for security reasons; set the following
	// environment variables to make the OpenStack testing work:
	//  access-key: $OS_USERNAME
	//  secret-key: $OS_PASSWORD
	//
	attrs := coretesting.FakeConfig().Merge(coretesting.Attrs{
		"name":           "sample-" + randomName(),
		"type":           "openstack",
		"auth-mode":      "userpass",
		"control-bucket": "juju-test-" + randomName(),
		"username":       cred.User,
		"password":       cred.Secrets,
		"region":         cred.Region,
		"auth-url":       cred.URL,
		"tenant-name":    cred.TenantName,
	})
	return attrs
}
Beispiel #22
0
func (suite *EnvironProviderSuite) TestUnknownAttrsContainAgentName(c *gc.C) {
	testJujuHome := c.MkDir()
	defer osenv.SetJujuHome(osenv.SetJujuHome(testJujuHome))
	attrs := testing.FakeConfig().Merge(testing.Attrs{
		"type":        "maas",
		"maas-oauth":  "aa:bb:cc",
		"maas-server": "http://maas.testing.invalid/maas/",
	})
	config, err := config.New(config.NoDefaults, attrs)
	c.Assert(err, gc.IsNil)

	ctx := testing.Context(c)
	environ, err := suite.makeEnviron().Provider().Prepare(ctx, config)
	c.Assert(err, gc.IsNil)

	preparedConfig := environ.Config()
	unknownAttrs := preparedConfig.UnknownAttrs()

	uuid, ok := unknownAttrs["maas-agent-name"]

	c.Assert(ok, jc.IsTrue)
	c.Assert(uuid, jc.Satisfies, utils.IsValidUUIDString)
}
Beispiel #23
0
func (t configTest) check(c *gc.C) {
	attrs := testing.FakeConfig().Merge(testing.Attrs{
		"type":           "ec2",
		"control-bucket": "x",
	}).Merge(t.config)
	cfg, err := config.New(config.NoDefaults, attrs)
	c.Assert(err, gc.IsNil)
	e, err := environs.New(cfg)
	if t.change != nil {
		c.Assert(err, gc.IsNil)

		// Testing a change in configuration.
		var old, changed, valid *config.Config
		ec2env := e.(*environ)
		old = ec2env.ecfg().Config
		changed, err = old.Apply(t.change)
		c.Assert(err, gc.IsNil)

		// Keep err for validation below.
		valid, err = providerInstance.Validate(changed, old)
		if err == nil {
			err = ec2env.SetConfig(valid)
		}
	}
	if t.err != "" {
		c.Check(err, gc.ErrorMatches, t.err)
		return
	}
	c.Assert(err, gc.IsNil)

	ecfg := e.(*environ).ecfg()
	c.Assert(ecfg.Name(), gc.Equals, "testenv")
	c.Assert(ecfg.controlBucket(), gc.Equals, "x")
	if t.region != "" {
		c.Assert(ecfg.region(), gc.Equals, t.region)
	}
	if t.accessKey != "" {
		c.Assert(ecfg.accessKey(), gc.Equals, t.accessKey)
		c.Assert(ecfg.secretKey(), gc.Equals, t.secretKey)
		expected := map[string]string{
			"access-key": t.accessKey,
			"secret-key": t.secretKey,
		}
		c.Assert(err, gc.IsNil)
		actual, err := e.Provider().SecretAttrs(ecfg.Config)
		c.Assert(err, gc.IsNil)
		c.Assert(expected, gc.DeepEquals, actual)
	} else {
		c.Assert(ecfg.accessKey(), gc.DeepEquals, testAuth.AccessKey)
		c.Assert(ecfg.secretKey(), gc.DeepEquals, testAuth.SecretKey)
	}
	if t.firewallMode != "" {
		c.Assert(ecfg.FirewallMode(), gc.Equals, t.firewallMode)
	}
	for name, expect := range t.expect {
		actual, found := ecfg.UnknownAttrs()[name]
		c.Check(found, gc.Equals, true)
		c.Check(actual, gc.Equals, expect)
	}

	// check storage bucket is configured correctly
	env := e.(*environ)
	c.Assert(env.Storage().(*ec2storage).bucket.Region.Name, gc.Equals, ecfg.region())
}
Beispiel #24
0
func (t configTest) check(c *gc.C) {
	attrs := testing.FakeConfig().Merge(testing.Attrs{
		"type":           "openstack",
		"control-bucket": "x",
	}).Merge(t.config)

	cfg, err := config.New(config.NoDefaults, attrs)
	c.Assert(err, gc.IsNil)

	// Set environment variables if any.
	savedVars := make(map[string]string)
	if t.envVars != nil {
		for k, v := range t.envVars {
			savedVars[k] = os.Getenv(k)
			os.Setenv(k, v)
		}
	}
	defer restoreEnvVars(savedVars)

	e, err := environs.New(cfg)
	if t.change != nil {
		c.Assert(err, gc.IsNil)

		// Testing a change in configuration.
		var old, changed, valid *config.Config
		osenv := e.(*environ)
		old = osenv.ecfg().Config
		changed, err = old.Apply(t.change)
		c.Assert(err, gc.IsNil)

		// Keep err for validation below.
		valid, err = providerInstance.Validate(changed, old)
		if err == nil {
			err = osenv.SetConfig(valid)
		}
	}
	if t.err != "" {
		c.Check(err, gc.ErrorMatches, t.err)
		return
	}
	c.Assert(err, gc.IsNil)

	ecfg := e.(*environ).ecfg()
	c.Assert(ecfg.Name(), gc.Equals, "testenv")
	c.Assert(ecfg.controlBucket(), gc.Equals, "x")
	if t.region != "" {
		c.Assert(ecfg.region(), gc.Equals, t.region)
	}
	if t.authMode != "" {
		c.Assert(ecfg.authMode(), gc.Equals, t.authMode)
	}
	if t.accessKey != "" {
		c.Assert(ecfg.accessKey(), gc.Equals, t.accessKey)
	}
	if t.secretKey != "" {
		c.Assert(ecfg.secretKey(), gc.Equals, t.secretKey)
	}
	if t.username != "" {
		c.Assert(ecfg.username(), gc.Equals, t.username)
		c.Assert(ecfg.password(), gc.Equals, t.password)
		c.Assert(ecfg.tenantName(), gc.Equals, t.tenantName)
		c.Assert(ecfg.authURL(), gc.Equals, t.authURL)
		expected := map[string]string{
			"username":    t.username,
			"password":    t.password,
			"tenant-name": t.tenantName,
		}
		c.Assert(err, gc.IsNil)
		actual, err := e.Provider().SecretAttrs(ecfg.Config)
		c.Assert(err, gc.IsNil)
		c.Assert(expected, gc.DeepEquals, actual)
	}
	if t.firewallMode != "" {
		c.Assert(ecfg.FirewallMode(), gc.Equals, t.firewallMode)
	}
	c.Assert(ecfg.useFloatingIP(), gc.Equals, t.useFloatingIP)
	c.Assert(ecfg.useDefaultSecurityGroup(), gc.Equals, t.useDefaultSecurityGroup)
	c.Assert(ecfg.network(), gc.Equals, t.network)
	// Default should be true
	expectedHostnameVerification := true
	if t.sslHostnameSet {
		expectedHostnameVerification = t.sslHostnameVerification
	}
	c.Assert(ecfg.SSLHostnameVerification(), gc.Equals, expectedHostnameVerification)
	for name, expect := range t.expect {
		actual, found := ecfg.UnknownAttrs()[name]
		c.Check(found, gc.Equals, true)
		c.Check(actual, gc.Equals, expect)
	}
}
Beispiel #25
0
func newConfig(c *gc.C, attrs coretesting.Attrs) *config.Config {
	attrs = coretesting.FakeConfig().Merge(attrs)
	cfg, err := config.New(config.UseDefaults, attrs)
	c.Assert(err, gc.IsNil)
	return cfg
}
Beispiel #26
0
func minimalConfigValues() map[string]interface{} {
	return testing.FakeConfig().Merge(testing.Attrs{
		"name": "test",
		"type": provider.Local,
	})
}
Beispiel #27
0
func minimalConfig(c *gc.C) *config.Config {
	cfg, err := config.New(config.NoDefaults, testing.FakeConfig())
	c.Assert(err, gc.IsNil)
	c.Assert(cfg, gc.NotNil)
	return cfg
}
Beispiel #28
0
		url, err := source.URL("")
		c.Assert(err, gc.IsNil)
		urls[i] = url
	}
	// The control bucket URL contains the bucket name.
	c.Check(strings.Contains(urls[0], ec2.ControlBucketName(env)+"/images"), jc.IsTrue)
	c.Assert(urls[1], gc.Equals, fmt.Sprintf("http://cloud-images.ubuntu.com/%s/", officialSourcePath))
}

func (t *ProviderSuite) TestGetImageMetadataSources(c *gc.C) {
	t.assertGetImageMetadataSources(c, "", "releases")
	t.assertGetImageMetadataSources(c, "released", "releases")
	t.assertGetImageMetadataSources(c, "daily", "daily")
}

var localConfigAttrs = coretesting.FakeConfig().Merge(coretesting.Attrs{
	"name":           "sample",
	"type":           "ec2",
	"region":         "test",
	"control-bucket": "test-bucket",
	"access-key":     "x",
	"secret-key":     "x",
	"agent-version":  version.Current.Number.String(),
})

func registerLocalTests() {
	// N.B. Make sure the region we use here
	// has entries in the images/query txt files.
	aws.Regions["test"] = aws.Region{
		Name: "test",
	}
Beispiel #29
0
func (t *LiveTests) TestInstanceGroups(c *gc.C) {
	t.PrepareOnce(c)
	ec2conn := ec2.EnvironEC2(t.Env)

	groups := amzec2.SecurityGroupNames(
		ec2.JujuGroupName(t.Env),
		ec2.MachineGroupName(t.Env, "98"),
		ec2.MachineGroupName(t.Env, "99"),
	)
	info := make([]amzec2.SecurityGroupInfo, len(groups))

	// Create a group with the same name as the juju group
	// but with different permissions, to check that it's deleted
	// and recreated correctly.
	oldJujuGroup := createGroup(c, ec2conn, groups[0].Name, "old juju group")

	// Add two permissions: one is required and should be left alone;
	// the other is not and should be deleted.
	// N.B. this is unfortunately sensitive to the actual set of permissions used.
	_, err := ec2conn.AuthorizeSecurityGroup(oldJujuGroup,
		[]amzec2.IPPerm{
			{
				Protocol:  "tcp",
				FromPort:  22,
				ToPort:    22,
				SourceIPs: []string{"0.0.0.0/0"},
			},
			{
				Protocol:  "udp",
				FromPort:  4321,
				ToPort:    4322,
				SourceIPs: []string{"3.4.5.6/32"},
			},
		})
	c.Assert(err, gc.IsNil)

	inst0, _ := testing.AssertStartInstance(c, t.Env, "98")
	defer t.Env.StopInstances([]instance.Instance{inst0})

	// Create a same-named group for the second instance
	// before starting it, to check that it's reused correctly.
	oldMachineGroup := createGroup(c, ec2conn, groups[2].Name, "old machine group")

	inst1, _ := testing.AssertStartInstance(c, t.Env, "99")
	defer t.Env.StopInstances([]instance.Instance{inst1})

	groupsResp, err := ec2conn.SecurityGroups(groups, nil)
	c.Assert(err, gc.IsNil)
	c.Assert(groupsResp.Groups, gc.HasLen, len(groups))

	// For each group, check that it exists and record its id.
	for i, group := range groups {
		found := false
		for _, g := range groupsResp.Groups {
			if g.Name == group.Name {
				groups[i].Id = g.Id
				info[i] = g
				found = true
				break
			}
		}
		if !found {
			c.Fatalf("group %q not found", group.Name)
		}
	}

	// The old juju group should have been reused.
	c.Check(groups[0].Id, gc.Equals, oldJujuGroup.Id)

	// Check that it authorizes the correct ports and there
	// are no extra permissions (in particular we are checking
	// that the unneeded permission that we added earlier
	// has been deleted).
	perms := info[0].IPPerms
	c.Assert(perms, gc.HasLen, 6)
	checkPortAllowed(c, perms, 22) // SSH
	checkPortAllowed(c, perms, coretesting.FakeConfig()["state-port"].(int))
	checkPortAllowed(c, perms, coretesting.FakeConfig()["api-port"].(int))
	checkSecurityGroupAllowed(c, perms, groups[0])

	// The old machine group should have been reused also.
	c.Check(groups[2].Id, gc.Equals, oldMachineGroup.Id)

	// Check that each instance is part of the correct groups.
	resp, err := ec2conn.Instances([]string{string(inst0.Id()), string(inst1.Id())}, nil)
	c.Assert(err, gc.IsNil)
	c.Assert(resp.Reservations, gc.HasLen, 2)
	for _, r := range resp.Reservations {
		c.Assert(r.Instances, gc.HasLen, 1)
		// each instance must be part of the general juju group.
		inst := r.Instances[0]
		msg := gc.Commentf("instance %#v", inst)
		c.Assert(hasSecurityGroup(inst, groups[0]), gc.Equals, true, msg)
		switch instance.Id(inst.InstanceId) {
		case inst0.Id():
			c.Assert(hasSecurityGroup(inst, groups[1]), gc.Equals, true, msg)
			c.Assert(hasSecurityGroup(inst, groups[2]), gc.Equals, false, msg)
		case inst1.Id():
			c.Assert(hasSecurityGroup(inst, groups[2]), gc.Equals, true, msg)
			c.Assert(hasSecurityGroup(inst, groups[1]), gc.Equals, false, msg)
		default:
			c.Errorf("unknown instance found: %v", inst)
		}
	}

	// Check that listing those instances finds them using the groups
	instIds := []instance.Id{inst0.Id(), inst1.Id()}
	idsFromInsts := func(insts []instance.Instance) (ids []instance.Id) {
		for _, inst := range insts {
			ids = append(ids, inst.Id())
		}
		return ids
	}
	insts, err := t.Env.Instances(instIds)
	c.Assert(err, gc.IsNil)
	c.Assert(instIds, jc.SameContents, idsFromInsts(insts))
	allInsts, err := t.Env.AllInstances()
	c.Assert(err, gc.IsNil)
	c.Assert(instIds, jc.SameContents, idsFromInsts(allInsts))
}
Beispiel #30
0
// makeConfigMap creates a minimal map of standard configuration items,
// adds the given extra items to that and returns it.
func makeConfigMap(extra map[string]interface{}) map[string]interface{} {
	return testing.FakeConfig().Merge(testing.Attrs{
		"name": "testenv",
		"type": "azure",
	}).Merge(extra)
}