Exemplo n.º 1
0
func (s *JujuHomeSuite) TestErrorHome(c *C) {
	// Invalid juju home leads to panic when retrieving.
	f := func() { _ = config.JujuHome() }
	c.Assert(f, PanicMatches, "juju home hasn't been initialized")
	f = func() { _ = config.JujuHomePath("environments.yaml") }
	c.Assert(f, PanicMatches, "juju home hasn't been initialized")
}
Exemplo n.º 2
0
// MakeFakeHomeNoEnvironments creates a new temporary directory through the
// test checker, and overrides the HOME environment variable to point to this
// new temporary directory.
//
// No ~/.juju/environments.yaml exists, but CAKeys are written for each of the
// 'certNames' specified, and the id_rsa.pub file is written to to the .ssh
// dir.
func MakeFakeHomeNoEnvironments(c *C, certNames ...string) *FakeHome {
	fake := MakeEmptyFakeHome(c)

	for _, name := range certNames {
		err := ioutil.WriteFile(config.JujuHomePath(name+"-cert.pem"), []byte(CACert), 0600)
		c.Assert(err, IsNil)
		err = ioutil.WriteFile(config.JujuHomePath(name+"-private-key.pem"), []byte(CAKey), 0600)
		c.Assert(err, IsNil)
	}

	err := os.Mkdir(HomePath(".ssh"), 0777)
	c.Assert(err, IsNil)
	err = ioutil.WriteFile(HomePath(".ssh", "id_rsa.pub"), []byte("auth key\n"), 0666)
	c.Assert(err, IsNil)

	return fake
}
Exemplo n.º 3
0
// MakeFakeHome creates a new temporary directory through the test checker,
// and overrides the HOME environment variable to point to this new temporary
// directory.
//
// A new ~/.juju/environments.yaml file is created with the content of the
// `envConfig` parameter, and CAKeys are written for each of the 'certNames'
// specified.
func MakeFakeHome(c *C, envConfig string, certNames ...string) *FakeHome {
	fake := MakeFakeHomeNoEnvironments(c, certNames...)

	envs := config.JujuHomePath("environments.yaml")
	err := ioutil.WriteFile(envs, []byte(envConfig), 0644)
	c.Assert(err, IsNil)

	return fake
}
Exemplo n.º 4
0
func (s *JujuConnSuite) setUpConn(c *C) {
	if s.RootDir != "" {
		panic("JujuConnSuite.setUpConn without teardown")
	}
	s.RootDir = c.MkDir()
	s.oldHome = os.Getenv("HOME")
	home := filepath.Join(s.RootDir, "/home/ubuntu")
	err := os.MkdirAll(home, 0777)
	c.Assert(err, IsNil)
	os.Setenv("HOME", home)

	dataDir := filepath.Join(s.RootDir, "/var/lib/juju")
	err = os.MkdirAll(dataDir, 0777)
	c.Assert(err, IsNil)

	yaml := []byte(fmt.Sprintf(envConfig, version.Current.Number))
	err = ioutil.WriteFile(config.JujuHomePath("environments.yaml"), yaml, 0600)
	c.Assert(err, IsNil)

	err = ioutil.WriteFile(config.JujuHomePath("dummyenv-cert.pem"), []byte(testing.CACert), 0666)
	c.Assert(err, IsNil)

	err = ioutil.WriteFile(config.JujuHomePath("dummyenv-private-key.pem"), []byte(testing.CAKey), 0600)
	c.Assert(err, IsNil)

	environ, err := environs.NewFromName("dummyenv")
	c.Assert(err, IsNil)
	// sanity check we've got the correct environment.
	c.Assert(environ.Name(), Equals, "dummyenv")
	c.Assert(environs.Bootstrap(environ, constraints.Value{}), IsNil)

	s.BackingState = environ.(GetStater).GetStateInAPIServer()

	conn, err := juju.NewConn(environ)
	c.Assert(err, IsNil)
	s.Conn = conn
	s.State = conn.State

	apiConn, err := juju.NewAPIConn(environ, api.DialOpts{})
	c.Assert(err, IsNil)
	s.APIConn = apiConn
	s.APIState = apiConn.State
	s.environ = environ
}
Exemplo n.º 5
0
// WriteConfig writes a juju config file to the "home" directory.
func (s *JujuConnSuite) WriteConfig(configData string) {
	if s.RootDir == "" {
		panic("SetUpTest has not been called; will not overwrite $JUJU_HOME/environments.yaml")
	}
	path := config.JujuHomePath("environments.yaml")
	err := ioutil.WriteFile(path, []byte(configData), 0600)
	if err != nil {
		panic(err)
	}
}
Exemplo n.º 6
0
// ensureCertOwner checks to make sure that the cert files created
// by the bootstrap command are owned by the user and not root.
func (env *localEnviron) ensureCertOwner() error {
	files := []string{
		config.JujuHomePath(env.name + "-cert.pem"),
		config.JujuHomePath(env.name + "-private-key.pem"),
	}

	uid, gid, err := sudoCallerIds()
	if err != nil {
		return err
	}
	if uid != 0 || gid != 0 {
		for _, filename := range files {
			if err := os.Chown(filename, uid, gid); err != nil {
				return err
			}
		}
	}
	return nil
}
Exemplo n.º 7
0
func (s *ValidateMetadataSuite) TestEc2LocalMetadataUsingEnvironment(c *gc.C) {
	s.setupEc2LocalMetadata(c, "us-east-1")
	ctx := coretesting.Context(c)
	metadataDir := config.JujuHomePath("")
	code := cmd.Main(
		&ValidateImageMetadataCommand{}, ctx, []string{"-e", "ec2", "-d", metadataDir},
	)
	c.Assert(code, gc.Equals, 0)
	errOut := ctx.Stdout.(*bytes.Buffer).String()
	strippedOut := strings.Replace(errOut, "\n", "", -1)
	c.Check(strippedOut, gc.Matches, `matching image ids for region "us-east-1":.*`)
}
Exemplo n.º 8
0
func (*EnvironsCertSuite) TestWriteCertAndKey(c *C) {
	defer testing.MakeEmptyFakeHome(c).Restore()

	// Ensure that the juju home path is different
	// from $HOME/.juju to check that WriteCertAndKey
	// isn't just using $HOME.
	config.SetJujuHome(c.MkDir())

	cert, key := []byte("a cert"), []byte("a key")
	err := environs.WriteCertAndKey("foo", cert, key)
	c.Assert(err, IsNil)

	// Check that the generated CA key has been written correctly.
	caCertPEM, err := ioutil.ReadFile(config.JujuHomePath("foo-cert.pem"))
	c.Assert(err, IsNil)
	c.Assert(caCertPEM, DeepEquals, cert)

	caKeyPEM, err := ioutil.ReadFile(config.JujuHomePath("foo-private-key.pem"))
	c.Assert(err, IsNil)
	c.Assert(caKeyPEM, DeepEquals, key)

}
Exemplo n.º 9
0
func writeJsonFile(imparams imageMetadataParams, filename, boilerplate string) error {
	t := template.Must(template.New("").Parse(boilerplate))
	var metadata bytes.Buffer
	if err := t.Execute(&metadata, imparams); err != nil {
		panic(fmt.Errorf("cannot generate %s metdata: %v", filename, err))
	}
	data := metadata.Bytes()
	path := config.JujuHomePath(filename)
	if err := ioutil.WriteFile(path, data, 0666); err != nil {
		return err
	}
	return nil
}
Exemplo n.º 10
0
func (s *ValidateSuite) TestNoMatch(c *gc.C) {
	s.makeLocalMetadata(c, "1234", "region-2", "raring", "some-auth-url")
	metadataDir := config.JujuHomePath("")
	params := &MetadataLookupParams{
		Region:        "region-2",
		Series:        "precise",
		Architectures: []string{"amd64"},
		Endpoint:      "some-auth-url",
		BaseURLs:      []string{"file://" + metadataDir},
	}
	_, err := ValidateImageMetadata(params)
	c.Assert(err, gc.Not(gc.IsNil))
}
Exemplo n.º 11
0
func (s *ValidateMetadataSuite) TestEc2LocalMetadataWithManualParams(c *gc.C) {
	s.setupEc2LocalMetadata(c, "us-west-1")
	ctx := coretesting.Context(c)
	metadataDir := config.JujuHomePath("")
	code := cmd.Main(
		&ValidateImageMetadataCommand{}, ctx, []string{
			"-p", "ec2", "-s", "precise", "-r", "us-west-1",
			"-u", "https://ec2.us-west-1.amazonaws.com", "-d", metadataDir},
	)
	c.Assert(code, gc.Equals, 0)
	errOut := ctx.Stdout.(*bytes.Buffer).String()
	strippedOut := strings.Replace(errOut, "\n", "", -1)
	c.Check(strippedOut, gc.Matches, `matching image ids for region "us-west-1":.*`)
}
Exemplo n.º 12
0
func (s *ValidateMetadataSuite) TestOpenstackLocalMetadataWithManualParams(c *gc.C) {
	s.makeLocalMetadata(c, "1234", "region-2", "raring", "some-auth-url")
	ctx := coretesting.Context(c)
	metadataDir := config.JujuHomePath("")
	code := cmd.Main(
		&ValidateImageMetadataCommand{}, ctx, []string{
			"-p", "openstack", "-s", "raring", "-r", "region-2",
			"-u", "some-auth-url", "-d", metadataDir},
	)
	c.Assert(code, gc.Equals, 0)
	errOut := ctx.Stdout.(*bytes.Buffer).String()
	strippedOut := strings.Replace(errOut, "\n", "", -1)
	c.Check(strippedOut, gc.Matches, `matching image ids for region "region-2":.*`)
}
Exemplo n.º 13
0
func (s *ValidateMetadataSuite) TestEc2LocalMetadataNoMatch(c *gc.C) {
	s.setupEc2LocalMetadata(c, "us-east-1")
	ctx := coretesting.Context(c)
	metadataDir := config.JujuHomePath("")
	code := cmd.Main(
		&ValidateImageMetadataCommand{}, ctx, []string{
			"-p", "ec2", "-s", "raring", "-r", "us-west-1",
			"-u", "https://ec2.us-west-1.amazonaws.com", "-d", metadataDir},
	)
	c.Assert(code, gc.Equals, 1)
	code = cmd.Main(
		&ValidateImageMetadataCommand{}, ctx, []string{
			"-p", "ec2", "-s", "precise", "-r", "region",
			"-u", "https://ec2.region.amazonaws.com", "-d", metadataDir},
	)
	c.Assert(code, gc.Equals, 1)
}
Exemplo n.º 14
0
func (s *ValidateMetadataSuite) TestOpenstackLocalMetadataNoMatch(c *gc.C) {
	s.makeLocalMetadata(c, "1234", "region-2", "raring", "some-auth-url")
	ctx := coretesting.Context(c)
	metadataDir := config.JujuHomePath("")
	code := cmd.Main(
		&ValidateImageMetadataCommand{}, ctx, []string{
			"-p", "openstack", "-s", "precise", "-r", "region-2",
			"-u", "some-auth-url", "-d", metadataDir},
	)
	c.Assert(code, gc.Equals, 1)
	code = cmd.Main(
		&ValidateImageMetadataCommand{}, ctx, []string{
			"-p", "openstack", "-s", "raring", "-r", "region-3",
			"-u", "some-auth-url", "-d", metadataDir},
	)
	c.Assert(code, gc.Equals, 1)
}
Exemplo n.º 15
0
// MakeBoilerplate exists so it can be called by tests. See Boilerplate above. It provides an option to retain
// the streams directories when writing the generated metadata files.
func MakeBoilerplate(name, series string, im *ImageMetadata, cloudSpec *CloudSpec, flattenPath bool) ([]string, error) {
	indexFileName := defaultIndexFileName
	imageFileName := defaultImageFileName
	if name != "" {
		indexFileName = fmt.Sprintf("%s-%s", name, indexFileName)
		imageFileName = fmt.Sprintf("%s-%s", name, imageFileName)
	}
	now := time.Now()
	imparams := imageMetadataParams{
		Id:            im.Id,
		Arch:          im.Arch,
		Region:        cloudSpec.Region,
		URL:           cloudSpec.Endpoint,
		Path:          streamsDir,
		ImageFileName: imageFileName,
		Updated:       now.Format(time.RFC1123Z),
		VersionKey:    now.Format("20060102"),
	}

	var err error
	imparams.Version, err = seriesVersion(series)
	if err != nil {
		return nil, fmt.Errorf("invalid series %q", series)
	}

	if !flattenPath {
		streamsPath := config.JujuHomePath(streamsDir)
		if err = os.MkdirAll(streamsPath, 0755); err != nil {
			return nil, err
		}
		indexFileName = filepath.Join(streamsDir, indexFileName)
		imageFileName = filepath.Join(streamsDir, imageFileName)
	}
	err = writeJsonFile(imparams, indexFileName, indexBoilerplate)
	if err != nil {
		return nil, err
	}
	err = writeJsonFile(imparams, imageFileName, productBoilerplate)
	if err != nil {
		return nil, err
	}
	return []string{indexFileName, imageFileName}, nil
}
Exemplo n.º 16
0
// Validate implements environs.EnvironProvider.Validate.
func (provider environProvider) Validate(cfg, old *config.Config) (valid *config.Config, err error) {
	// Check for valid changes for the base config values.
	if err := config.Validate(cfg, old); err != nil {
		return nil, err
	}
	validated, err := cfg.ValidateUnknownAttrs(configFields, configDefaults)
	if err != nil {
		return nil, err
	}
	localConfig := newEnvironConfig(cfg, validated)
	// Before potentially creating directories, make sure that the
	// root directory has not changed.
	if old != nil {
		oldLocalConfig, err := provider.newConfig(old)
		if err != nil {
			return nil, fmt.Errorf("old config is not a valid local config: %v", old)
		}
		if localConfig.rootDir() != oldLocalConfig.rootDir() {
			return nil, fmt.Errorf("cannot change root-dir from %q to %q",
				oldLocalConfig.rootDir(),
				localConfig.rootDir())
		}
		if localConfig.storagePort() != oldLocalConfig.storagePort() {
			return nil, fmt.Errorf("cannot change storage-port from %v to %v",
				oldLocalConfig.storagePort(),
				localConfig.storagePort())
		}
		if localConfig.sharedStoragePort() != oldLocalConfig.sharedStoragePort() {
			return nil, fmt.Errorf("cannot change shared-storage-port from %v to %v",
				oldLocalConfig.sharedStoragePort(),
				localConfig.sharedStoragePort())
		}
	}
	dir := utils.NormalizePath(localConfig.rootDir())
	if dir == "." {
		dir = config.JujuHomePath(cfg.Name())
		localConfig.attrs["root-dir"] = dir
	}

	// Apply the coerced unknown values back into the config.
	return cfg.Apply(localConfig.attrs)
}
Exemplo n.º 17
0
// breakJuju writes a dummy environment with incomplete configuration.
// environMethod is called.
func breakJuju(c *C, environMethod string) (msg string) {
	path := config.JujuHomePath("environments.yaml")
	err := ioutil.WriteFile(path, []byte(brokenConfig), 0666)
	c.Assert(err, IsNil)
	return fmt.Sprintf("environment configuration has no admin-secret")
}
Exemplo n.º 18
0
func environsPath(path string) string {
	if path == "" {
		path = config.JujuHomePath("environments.yaml")
	}
	return path
}
Exemplo n.º 19
0
func (s *JujuHomeSuite) TestHomePath(c *C) {
	testJujuHome := c.MkDir()
	defer config.SetJujuHome(config.SetJujuHome(testJujuHome))
	envPath := config.JujuHomePath("environments.yaml")
	c.Assert(envPath, Equals, filepath.Join(testJujuHome, "environments.yaml"))
}