Beispiel #1
0
func (s *MongoSuite) TestMakeJournalDirs(c *gc.C) {
	dir := c.MkDir()
	err := mongo.MakeJournalDirs(dir)
	c.Assert(err, gc.IsNil)

	testJournalDirs(dir, c)
}
Beispiel #2
0
func extBundleDirPath(c *gc.C, dirpath string) string {
	path := filepath.Join(c.MkDir(), "bundle.charm")
	cmd := exec.Command("/bin/sh", "-c", fmt.Sprintf("cd %s; zip --fifo --symlinks -r %s .", dirpath, path))
	output, err := cmd.CombinedOutput()
	c.Assert(err, gc.IsNil, gc.Commentf("Command output: %s", output))
	return path
}
Beispiel #3
0
func (s *preallocSuite) TestPreallocFilesWriteErrors(c *gc.C) {
	dir := c.MkDir()
	prefix := filepath.Join(dir, "test.")
	err := ioutil.WriteFile(prefix+"0", nil, 0644)
	c.Assert(err, gc.IsNil)
	err = ioutil.WriteFile(prefix+"1", nil, 0644)
	c.Assert(err, gc.IsNil)

	var called int
	s.PatchValue(mongo.PreallocFile, func(filename string, size int) (bool, error) {
		var created bool
		var err error
		called++
		if called == 2 {
			created = true
			err = fmt.Errorf("failed to zero test.1")
		}
		return created, err
	})

	err = mongo.PreallocFiles(prefix, 4096, 8192)
	c.Assert(err, gc.ErrorMatches, "failed to zero test.1")

	// test.0 still exists because we said we didn't
	// create it (i.e. it already existed)
	_, err = os.Stat(prefix + "0")
	c.Assert(err, gc.IsNil)

	// test.1 no longer exists because we said we created
	// it, but then failed to write to it.
	_, err = os.Stat(prefix + "1")
	c.Assert(err, jc.Satisfies, os.IsNotExist)
}
func (s *ValidateImageMetadataSuite) SetUpTest(c *gc.C) {
	s.FakeJujuHomeSuite.SetUpTest(c)
	s.metadataDir = c.MkDir()
	coretesting.WriteEnvironments(c, metadataTestEnvConfig)
	s.PatchEnvironment("AWS_ACCESS_KEY_ID", "access")
	s.PatchEnvironment("AWS_SECRET_ACCESS_KEY", "secret")
}
Beispiel #5
0
func (*scriptSuite) TestDumpFileOnErrorScript(c *gc.C) {
	tempdir := c.MkDir()
	filename := filepath.Join(tempdir, "log.txt")
	err := ioutil.WriteFile(filename, []byte("abc"), 0644)
	c.Assert(err, gc.IsNil)

	dumpScript := shell.DumpFileOnErrorScript(filename)
	c.Logf("%s", dumpScript)
	run := func(command string) (stdout, stderr string) {
		var stdoutBuf, stderrBuf bytes.Buffer
		cmd := exec.Command("/bin/bash", "-s")
		cmd.Stdin = strings.NewReader(dumpScript + command)
		cmd.Stdout = &stdoutBuf
		cmd.Stderr = &stderrBuf
		cmd.Run()
		return stdoutBuf.String(), stderrBuf.String()
	}

	stdout, stderr := run("exit 0")
	c.Assert(stdout, gc.Equals, "")
	c.Assert(stderr, gc.Equals, "")

	stdout, stderr = run("exit 1")
	c.Assert(stdout, gc.Equals, "")
	c.Assert(stderr, gc.Equals, "abc")

	err = os.Remove(filename)
	c.Assert(err, gc.IsNil)
	stdout, stderr = run("exit 1")
	c.Assert(stdout, gc.Equals, "")
	c.Assert(stderr, gc.Equals, "")
}
Beispiel #6
0
func (s *PublishSuite) TestUnknownPushLocation(c *gc.C) {
	addMeta(c, s.branch, "")
	err := s.branch.Push(&bzr.PushAttr{Location: c.MkDir() + "/foo", Remember: true})
	c.Assert(err, gc.IsNil)
	_, err = s.runPublish(c)
	c.Assert(err, gc.ErrorMatches, `cannot infer charm URL from branch location: ".*/foo"`)
}
Beispiel #7
0
func (s *ServerSuite) TestBadCommandName(c *gc.C) {
	dir := c.MkDir()
	_, err := s.Call(c, jujuc.Request{"validCtx", dir, "", nil})
	c.Assert(err, gc.ErrorMatches, "bad request: command not specified")
	_, err = s.Call(c, jujuc.Request{"validCtx", dir, "witchcraft", nil})
	c.Assert(err, gc.ErrorMatches, `bad request: unknown command "witchcraft"`)
}
Beispiel #8
0
func (*metadataHelperSuite) TestResolveMetadata(c *gc.C) {
	var versionStrings = []string{"1.2.3-precise-amd64"}
	dir := c.MkDir()
	ttesting.MakeTools(c, dir, "releases", versionStrings)
	toolsList := coretools.List{{
		Version: version.MustParseBinary(versionStrings[0]),
		Size:    123,
		SHA256:  "abc",
	}}

	stor, err := filestorage.NewFileStorageReader(dir)
	c.Assert(err, gc.IsNil)
	err = tools.ResolveMetadata(stor, nil)
	c.Assert(err, gc.IsNil)

	// We already have size/sha256, so ensure that storage isn't consulted.
	countingStorage := &countingStorage{StorageReader: stor}
	metadata := tools.MetadataFromTools(toolsList)
	err = tools.ResolveMetadata(countingStorage, metadata)
	c.Assert(err, gc.IsNil)
	c.Assert(countingStorage.counter, gc.Equals, 0)

	// Now clear size/sha256, and check that it is called, and
	// the size/sha256 sum are updated.
	metadata[0].Size = 0
	metadata[0].SHA256 = ""
	err = tools.ResolveMetadata(countingStorage, metadata)
	c.Assert(err, gc.IsNil)
	c.Assert(countingStorage.counter, gc.Equals, 1)
	c.Assert(metadata[0].Size, gc.Not(gc.Equals), 0)
	c.Assert(metadata[0].SHA256, gc.Not(gc.Equals), "")
}
Beispiel #9
0
func (*metadataHelperSuite) TestReadWriteMetadata(c *gc.C) {
	metadata := []*tools.ToolsMetadata{{
		Release: "precise",
		Version: "1.2.3",
		Arch:    "amd64",
		Path:    "path1",
	}, {
		Release: "raring",
		Version: "1.2.3",
		Arch:    "amd64",
		Path:    "path2",
	}}

	stor, err := filestorage.NewFileStorageWriter(c.MkDir())
	c.Assert(err, gc.IsNil)
	out, err := tools.ReadMetadata(stor)
	c.Assert(out, gc.HasLen, 0)
	c.Assert(err, gc.IsNil) // non-existence is not an error
	err = tools.WriteMetadata(stor, metadata, tools.DoNotWriteMirrors)
	c.Assert(err, gc.IsNil)
	out, err = tools.ReadMetadata(stor)
	for _, md := range out {
		// FullPath is set by ReadMetadata.
		c.Assert(md.FullPath, gc.Not(gc.Equals), "")
		md.FullPath = ""
	}
	c.Assert(out, gc.DeepEquals, metadata)
}
Beispiel #10
0
func (s *simplestreamsSuite) assertWriteMetadata(c *gc.C, withMirrors bool) {
	var versionStrings = []string{
		"1.2.3-precise-amd64",
		"2.0.1-raring-amd64",
	}
	dir := c.MkDir()
	ttesting.MakeTools(c, dir, "releases", versionStrings)

	toolsList := coretools.List{
		{
			// If sha256/size is already known, do not recalculate
			Version: version.MustParseBinary("1.2.3-precise-amd64"),
			Size:    123,
			SHA256:  "abcd",
		}, {
			Version: version.MustParseBinary("2.0.1-raring-amd64"),
			// The URL is not used for generating metadata.
			URL: "bogus://",
		},
	}
	writer, err := filestorage.NewFileStorageWriter(dir)
	c.Assert(err, gc.IsNil)
	writeMirrors := tools.DoNotWriteMirrors
	if withMirrors {
		writeMirrors = tools.WriteMirrors
	}
	err = tools.MergeAndWriteMetadata(writer, toolsList, writeMirrors)
	c.Assert(err, gc.IsNil)
	metadata := ttesting.ParseMetadataFromDir(c, dir, withMirrors)
	assertMetadataMatches(c, dir, toolsList, metadata)
}
Beispiel #11
0
func (s *simplestreamsSuite) TestWriteMetadataMergeWithExisting(c *gc.C) {
	dir := c.MkDir()
	existingToolsList := coretools.List{
		{
			Version: version.MustParseBinary("1.2.3-precise-amd64"),
			Size:    123,
			SHA256:  "abc",
		}, {
			Version: version.MustParseBinary("2.0.1-raring-amd64"),
			Size:    456,
			SHA256:  "xyz",
		},
	}
	writer, err := filestorage.NewFileStorageWriter(dir)
	c.Assert(err, gc.IsNil)
	err = tools.MergeAndWriteMetadata(writer, existingToolsList, tools.DoNotWriteMirrors)
	c.Assert(err, gc.IsNil)
	newToolsList := coretools.List{
		existingToolsList[0],
		{
			Version: version.MustParseBinary("2.1.0-raring-amd64"),
			Size:    789,
			SHA256:  "def",
		},
	}
	err = tools.MergeAndWriteMetadata(writer, newToolsList, tools.DoNotWriteMirrors)
	c.Assert(err, gc.IsNil)
	requiredToolsList := append(existingToolsList, newToolsList[1])
	metadata := ttesting.ParseMetadataFromDir(c, dir, false)
	assertMetadataMatches(c, dir, requiredToolsList, metadata)
}
Beispiel #12
0
func (s *ManifestDeployerSuite) SetUpTest(c *gc.C) {
	s.BaseSuite.SetUpTest(c)
	s.bundles = &bundleReader{}
	s.targetPath = filepath.Join(c.MkDir(), "target")
	deployerPath := filepath.Join(c.MkDir(), "deployer")
	s.deployer = charm.NewManifestDeployer(s.targetPath, deployerPath, s.bundles)
}
Beispiel #13
0
// mockShellCommand creates a new command with the given
// name and contents, and patches $PATH so that it will be
// executed by preference. It returns the name of a file
// that is written by each call to the command - mockShellCalls
// can be used to retrieve the calls.
func mockShellCommand(c *gc.C, s *testing.CleanupSuite, name string) string {
	dir := c.MkDir()
	s.PatchEnvPathPrepend(dir)

	// Note the shell script produces output of the form:
	// +arg1+\n
	// +arg2+\n
	// ...
	// +argn+\n
	// -
	//
	// It would be nice if there was a simple way of unambiguously
	// quoting shell arguments, but this will do as long
	// as no argument contains a newline character.
	outputFile := filepath.Join(dir, name+".out")
	contents := `#!/bin/sh
{
	for i in "$@"; do
		echo +"$i"+
	done
	echo -
} >> ` + utils.ShQuote(outputFile) + `
`
	err := ioutil.WriteFile(filepath.Join(dir, name), []byte(contents), 0755)
	c.Assert(err, gc.IsNil)
	return outputFile
}
Beispiel #14
0
func (s *MongoSuite) TestUpstartServiceIPv6(c *gc.C) {
	dataDir := c.MkDir()

	svc, err := mongo.UpstartService("", dataDir, dataDir, mongo.JujuMongodPath, 1234, 1024)
	c.Assert(err, gc.IsNil)
	c.Assert(strings.Contains(svc.Conf.Cmd, "--ipv6"), jc.IsTrue)
}
Beispiel #15
0
func (b *buildSuite) SetUpTest(c *gc.C) {
	b.BaseSuite.SetUpTest(c)

	dir1 := c.MkDir()
	dir2 := c.MkDir()

	c.Log(dir1)
	c.Log(dir2)

	path := os.Getenv("PATH")
	os.Setenv("PATH", fmt.Sprintf("%s:%s:%s", dir1, dir2, path))

	// Make an executable file called "juju-test" in dir2.
	b.filePath = filepath.Join(dir2, "juju-test")
	err := ioutil.WriteFile(
		b.filePath,
		[]byte("doesn't matter, we don't execute it"),
		0755)
	c.Assert(err, gc.IsNil)

	cwd, err := os.Getwd()
	c.Assert(err, gc.IsNil)

	b.cwd = c.MkDir()
	err = os.Chdir(b.cwd)
	c.Assert(err, gc.IsNil)

	b.restore = func() {
		os.Setenv("PATH", path)
		os.Chdir(cwd)
	}
}
Beispiel #16
0
func (s *GitDirSuite) TestClone(c *gc.C) {
	repo, err := newRepo(c).Clone(c.MkDir())
	c.Assert(err, gc.IsNil)
	_, err = os.Stat(filepath.Join(repo.Path(), "some-file"))
	c.Assert(err, jc.Satisfies, os.IsNotExist)
	_, err = os.Stat(filepath.Join(repo.Path(), "some-dir"))
	c.Assert(err, jc.Satisfies, os.IsNotExist)
	dirty, err := repo.Dirty()
	c.Assert(err, gc.IsNil)
	c.Assert(dirty, jc.IsTrue)

	err = repo.AddAll()
	c.Assert(err, gc.IsNil)
	dirty, err = repo.Dirty()
	c.Assert(err, gc.IsNil)
	c.Assert(dirty, jc.IsTrue)
	err = repo.Commitf("blank overwrite")
	c.Assert(err, gc.IsNil)
	dirty, err = repo.Dirty()
	c.Assert(err, gc.IsNil)
	c.Assert(dirty, jc.IsFalse)

	lines, err := repo.Log()
	c.Assert(err, gc.IsNil)
	c.Assert(lines, gc.HasLen, 2)
	c.Assert(lines[0], gc.Matches, "[a-f0-9]{7} blank overwrite")
	c.Assert(lines[1], gc.Matches, "[a-f0-9]{7} im in ur repo committin ur files")
}
Beispiel #17
0
func (s *LocalRepoSuite) SetUpTest(c *gc.C) {
	s.FakeHomeSuite.SetUpTest(c)
	root := c.MkDir()
	s.repo = &charm.LocalRepository{Path: root}
	s.seriesPath = filepath.Join(root, "quantal")
	c.Assert(os.Mkdir(s.seriesPath, 0777), gc.IsNil)
}
Beispiel #18
0
func (s *storageSuite) SetUpSuite(c *gc.C) {
	s.LoggingSuite.SetUpSuite(c)

	var err error
	flockBin, err = exec.LookPath("flock")
	c.Assert(err, gc.IsNil)

	s.bin = c.MkDir()
	s.PatchEnvPathPrepend(s.bin)

	// Create a "sudo" command which shifts away the "-n", sets
	// SUDO_UID/SUDO_GID, and executes the remaining args.
	err = ioutil.WriteFile(filepath.Join(s.bin, "sudo"), []byte(
		"#!/bin/sh\nshift; export SUDO_UID=`id -u` SUDO_GID=`id -g`; exec \"$@\"",
	), 0755)
	c.Assert(err, gc.IsNil)
	restoreSshCommand := testing.PatchValue(&sshCommand, func(host string, command ...string) *ssh.Cmd {
		return s.sshCommand(c, host, command...)
	})
	s.AddSuiteCleanup(func(*gc.C) { restoreSshCommand() })

	// Create a new "flock" which calls the original, but in non-blocking mode.
	data := []byte(fmt.Sprintf("#!/bin/sh\nexec %s --nonblock \"$@\"", flockBin))
	err = ioutil.WriteFile(filepath.Join(s.bin, "flock"), data, 0755)
	c.Assert(err, gc.IsNil)
}
Beispiel #19
0
// installFakeSSH creates a fake "ssh" command in a new $PATH,
// updates $PATH, and returns a function to reset $PATH to its
// original value when called.
//
// input may be:
//    - nil (ignore input)
//    - a string (match input exactly)
// output may be:
//    - nil (no output)
//    - a string (stdout)
//    - a slice of strings, of length two (stdout, stderr)
func installFakeSSH(c *gc.C, input, output interface{}, rc int) testing.Restorer {
	fakebin := c.MkDir()
	ssh := filepath.Join(fakebin, "ssh")
	switch input := input.(type) {
	case nil:
	case string:
		sshexpectedinput := ssh + ".expected-input"
		err := ioutil.WriteFile(sshexpectedinput, []byte(input), 0644)
		c.Assert(err, gc.IsNil)
	default:
		c.Errorf("input has invalid type: %T", input)
	}
	var stdout, stderr string
	switch output := output.(type) {
	case nil:
	case string:
		stdout = fmt.Sprintf("cat<<EOF\n%s\nEOF", output)
	case []string:
		c.Assert(output, gc.HasLen, 2)
		stdout = fmt.Sprintf("cat<<EOF\n%s\nEOF", output[0])
		stderr = fmt.Sprintf("cat>&2<<EOF\n%s\nEOF", output[1])
	}
	script := fmt.Sprintf(sshscript, stdout, stderr, rc)
	err := ioutil.WriteFile(ssh, []byte(script), 0777)
	c.Assert(err, gc.IsNil)
	return testing.PatchEnvPathPrepend(fakebin)
}
Beispiel #20
0
func (*diskStoreSuite) TestWriteSmallerFile(c *gc.C) {
	dir := c.MkDir()
	store, err := configstore.NewDisk(dir)
	c.Assert(err, gc.IsNil)
	info := store.CreateInfo("someenv")
	endpoint := configstore.APIEndpoint{
		Addresses:   []string{"this", "is", "never", "validated", "here"},
		EnvironUUID: "90168e4c-2f10-4e9c-83c2-feedfacee5a9",
	}
	info.SetAPIEndpoint(endpoint)
	err = info.Write()
	c.Assert(err, gc.IsNil)

	newInfo, err := store.ReadInfo("someenv")
	c.Assert(err, gc.IsNil)
	// Now change the number of addresses to be shorter.
	endpoint.Addresses = []string{"just one"}
	newInfo.SetAPIEndpoint(endpoint)
	err = newInfo.Write()
	c.Assert(err, gc.IsNil)

	// We should be able to read in in fine.
	yaInfo, err := store.ReadInfo("someenv")
	c.Assert(err, gc.IsNil)
	c.Assert(yaInfo.APIEndpoint().Addresses, gc.DeepEquals, []string{"just one"})
}
Beispiel #21
0
func (s *BootstrapSuite) SetUpTest(c *gc.C) {
	s.BaseSuite.SetUpTest(c)
	s.MgoSuite.SetUpTest(c)
	s.dataDir = c.MkDir()
	s.logDir = c.MkDir()
	s.fakeEnsureMongo = fakeEnsure{}
}
Beispiel #22
0
func (*diskStoreSuite) TestCreate(c *gc.C) {
	dir := c.MkDir()
	store, err := configstore.NewDisk(dir)
	c.Assert(err, gc.IsNil)

	// Create some new environment info.
	info, err := store.CreateInfo("someenv")
	c.Assert(err, gc.IsNil)
	c.Assert(info.APIEndpoint(), gc.DeepEquals, configstore.APIEndpoint{})
	c.Assert(info.APICredentials(), gc.DeepEquals, configstore.APICredentials{})
	c.Assert(info.Initialized(), jc.IsFalse)
	data, err := ioutil.ReadFile(storePath(dir, "someenv"))
	c.Assert(err, gc.IsNil)
	c.Assert(data, gc.HasLen, 0)

	// Check that we can't create it twice.
	info, err = store.CreateInfo("someenv")
	c.Assert(err, gc.Equals, configstore.ErrEnvironInfoAlreadyExists)
	c.Assert(info, gc.IsNil)

	// Check that we can read it again.
	info, err = store.ReadInfo("someenv")
	c.Assert(err, gc.IsNil)
	c.Assert(info.Initialized(), jc.IsFalse)
}
Beispiel #23
0
func (s *clientSuite) TestAddLocalCharm(c *gc.C) {
	charmArchive := charmtesting.Charms.CharmArchive(c.MkDir(), "dummy")
	curl := charm.MustParseURL(
		fmt.Sprintf("local:quantal/%s-%d", charmArchive.Meta().Name, charmArchive.Revision()),
	)
	client := s.APIState.Client()

	// Test the sanity checks first.
	_, err := client.AddLocalCharm(charm.MustParseURL("cs:quantal/wordpress-1"), nil)
	c.Assert(err, gc.ErrorMatches, `expected charm URL with local: schema, got "cs:quantal/wordpress-1"`)

	// Upload an archive with its original revision.
	savedURL, err := client.AddLocalCharm(curl, charmArchive)
	c.Assert(err, gc.IsNil)
	c.Assert(savedURL.String(), gc.Equals, curl.String())

	// Upload a charm directory with changed revision.
	charmDir := charmtesting.Charms.ClonedDir(c.MkDir(), "dummy")
	charmDir.SetDiskRevision(42)
	savedURL, err = client.AddLocalCharm(curl, charmDir)
	c.Assert(err, gc.IsNil)
	c.Assert(savedURL.Revision, gc.Equals, 42)

	// Upload a charm directory again, revision should be bumped.
	savedURL, err = client.AddLocalCharm(curl, charmDir)
	c.Assert(err, gc.IsNil)
	c.Assert(savedURL.String(), gc.Equals, curl.WithRevision(43).String())
}
Beispiel #24
0
func (*diskStoreSuite) TestRead(c *gc.C) {
	dir := c.MkDir()
	err := os.Mkdir(storePath(dir, ""), 0700)
	c.Assert(err, gc.IsNil)
	err = ioutil.WriteFile(storePath(dir, "someenv"), []byte(sampleInfo), 0666)
	c.Assert(err, gc.IsNil)
	store, err := configstore.NewDisk(dir)
	c.Assert(err, gc.IsNil)
	info, err := store.ReadInfo("someenv")
	c.Assert(err, gc.IsNil)
	c.Assert(info.Initialized(), jc.IsTrue)
	c.Assert(info.APICredentials(), gc.DeepEquals, configstore.APICredentials{
		User:     "******",
		Password: "******",
	})
	c.Assert(info.APIEndpoint(), gc.DeepEquals, configstore.APIEndpoint{
		Addresses: []string{"example.com", "kremvax.ru"},
		CACert:    "first line\nsecond line",
	})
	c.Assert(info.Location(), gc.Equals, fmt.Sprintf("file %q", dir+"/environments/someenv.jenv"))
	c.Assert(info.BootstrapConfig(), gc.DeepEquals, map[string]interface{}{
		"secret": "blah",
		"arble":  "bletch",
	})
}
Beispiel #25
0
func (s *BundleSuite) TestBundleRevisionFile(c *gc.C) {
	charmDir := charmtesting.Charms.ClonedDirPath(c.MkDir(), "dummy")
	revPath := filepath.Join(charmDir, "revision")

	// Missing revision file
	err := os.Remove(revPath)
	c.Assert(err, gc.IsNil)

	bundle := extBundleDir(c, charmDir)
	c.Assert(bundle.Revision(), gc.Equals, 0)

	// Missing revision file with old revision in metadata
	file, err := os.OpenFile(filepath.Join(charmDir, "metadata.yaml"), os.O_WRONLY|os.O_APPEND, 0)
	c.Assert(err, gc.IsNil)
	_, err = file.Write([]byte("\nrevision: 1234\n"))
	c.Assert(err, gc.IsNil)

	bundle = extBundleDir(c, charmDir)
	c.Assert(bundle.Revision(), gc.Equals, 1234)

	// Revision file with bad content
	err = ioutil.WriteFile(revPath, []byte("garbage"), 0666)
	c.Assert(err, gc.IsNil)

	path := extBundleDirPath(c, charmDir)
	bundle, err = charm.ReadBundle(path)
	c.Assert(err, gc.ErrorMatches, "invalid revision file")
	c.Assert(bundle, gc.IsNil)
}
Beispiel #26
0
func (s *commonMachineSuite) SetUpTest(c *gc.C) {
	s.agentSuite.SetUpTest(c)
	s.TestSuite.SetUpTest(c)

	os.Remove(jujuRun) // ignore error; may not exist
	// Patch ssh user to avoid touching ~ubuntu/.ssh/authorized_keys.
	s.agentSuite.PatchValue(&authenticationworker.SSHUser, "")

	testpath := c.MkDir()
	s.agentSuite.PatchEnvPathPrepend(testpath)
	// mock out the start method so we can fake install services without sudo
	fakeCmd(filepath.Join(testpath, "start"))
	fakeCmd(filepath.Join(testpath, "stop"))

	s.agentSuite.PatchValue(&upstart.InitDir, c.MkDir())

	s.singularRecord = &singularRunnerRecord{}
	s.agentSuite.PatchValue(&newSingularRunner, s.singularRecord.newSingularRunner)
	s.agentSuite.PatchValue(&peergrouperNew, func(st *state.State) (worker.Worker, error) {
		return newDummyWorker(), nil
	})

	s.fakeEnsureMongo = fakeEnsure{}
	s.agentSuite.PatchValue(&ensureMongoServer, s.fakeEnsureMongo.fakeEnsureMongo)
	s.agentSuite.PatchValue(&maybeInitiateMongoServer, s.fakeEnsureMongo.fakeInitiateMongo)
}
Beispiel #27
0
func (s *StateFileSuite) TestStates(c *gc.C) {
	for i, t := range stateTests {
		c.Logf("test %d", i)
		path := filepath.Join(c.MkDir(), "uniter")
		file := uniter.NewStateFile(path)
		_, err := file.Read()
		c.Assert(err, gc.Equals, uniter.ErrNoStateFile)
		write := func() {
			err := file.Write(t.st.Started, t.st.Op, t.st.OpStep, t.st.Hook, t.st.CharmURL)
			c.Assert(err, gc.IsNil)
		}
		if t.err != "" {
			c.Assert(write, gc.PanicMatches, "invalid uniter state: "+t.err)
			err := utils.WriteYaml(path, &t.st)
			c.Assert(err, gc.IsNil)
			_, err = file.Read()
			c.Assert(err, gc.ErrorMatches, "cannot read charm state at .*: invalid uniter state: "+t.err)
			continue
		}
		write()
		st, err := file.Read()
		c.Assert(err, gc.IsNil)
		c.Assert(*st, gc.DeepEquals, t.st)
	}
}
Beispiel #28
0
func (s *MachineSuite) TestMachineEnvironWorker(c *gc.C) {
	proxyDir := c.MkDir()
	s.agentSuite.PatchValue(&machineenvironmentworker.ProxyDirectory, proxyDir)
	s.agentSuite.PatchValue(&apt.ConfFile, filepath.Join(proxyDir, "juju-apt-proxy"))

	s.primeAgent(c, version.Current, state.JobHostUnits)
	// Make sure there are some proxy settings to write.
	proxySettings := proxy.Settings{
		Http:  "http proxy",
		Https: "https proxy",
		Ftp:   "ftp proxy",
	}

	updateAttrs := config.ProxyConfigMap(proxySettings)

	err := s.State.UpdateEnvironConfig(updateAttrs, nil, nil)
	c.Assert(err, gc.IsNil)

	s.assertJobWithAPI(c, state.JobHostUnits, func(conf agent.Config, st *api.State) {
		for {
			select {
			case <-time.After(coretesting.LongWait):
				c.Fatalf("timeout while waiting for proxy settings to change")
			case <-time.After(10 * time.Millisecond):
				_, err := os.Stat(apt.ConfFile)
				if os.IsNotExist(err) {
					continue
				}
				c.Assert(err, gc.IsNil)
				return
			}
		}
	})
}
Beispiel #29
0
func (s *RelationerSuite) SetUpTest(c *gc.C) {
	s.JujuConnSuite.SetUpTest(c)
	var err error
	s.svc = s.AddTestingService(c, "u", s.AddTestingCharm(c, "riak"))
	c.Assert(err, gc.IsNil)
	rels, err := s.svc.Relations()
	c.Assert(err, gc.IsNil)
	c.Assert(rels, gc.HasLen, 1)
	s.rel = rels[0]
	_, unit := s.AddRelationUnit(c, "u/0")
	s.dirPath = c.MkDir()
	s.dir, err = relation.ReadStateDir(s.dirPath, s.rel.Id())
	c.Assert(err, gc.IsNil)
	s.hooks = make(chan hook.Info)

	password, err := utils.RandomPassword()
	c.Assert(err, gc.IsNil)
	err = unit.SetPassword(password)
	c.Assert(err, gc.IsNil)
	s.st = s.OpenAPIAs(c, unit.Tag(), password)
	s.uniter = s.st.Uniter()
	c.Assert(s.uniter, gc.NotNil)

	apiUnit, err := s.uniter.Unit(unit.Tag())
	c.Assert(err, gc.IsNil)
	apiRel, err := s.uniter.Relation(s.rel.Tag())
	c.Assert(err, gc.IsNil)
	s.apiRelUnit, err = apiRel.Unit(apiUnit)
	c.Assert(err, gc.IsNil)
}
Beispiel #30
0
func (s *identitySuite) TestWriteSystemIdentityFile(c *gc.C) {
	params := attributeParams
	params.DataDir = c.MkDir()
	conf, err := NewStateMachineConfig(params, servingInfo)
	c.Assert(err, gc.IsNil)
	err = WriteSystemIdentityFile(conf)
	c.Assert(err, gc.IsNil)

	contents, err := ioutil.ReadFile(conf.SystemIdentityPath())
	c.Assert(err, gc.IsNil)
	c.Check(string(contents), gc.Equals, servingInfo.SystemIdentity)

	fi, err := os.Stat(conf.SystemIdentityPath())
	c.Assert(err, gc.IsNil)
	c.Check(fi.Mode().Perm(), gc.Equals, os.FileMode(0600))

	// ensure that file is deleted when SystemIdentity is empty
	info := servingInfo
	info.SystemIdentity = ""
	conf, err = NewStateMachineConfig(params, info)
	c.Assert(err, gc.IsNil)
	err = WriteSystemIdentityFile(conf)
	c.Assert(err, gc.IsNil)

	fi, err = os.Stat(conf.SystemIdentityPath())
	c.Assert(err, gc.ErrorMatches, `stat .*: no such file or directory`)
}