Example #1
0
func (fix *SimpleToolsFixture) SetUp(c *gc.C, dataDir string) {
	fix.BaseSuite.SetUpTest(c)
	fix.dataDir = dataDir
	fix.initDir = c.MkDir()
	fix.logDir = c.MkDir()
	toolsDir := tools.SharedToolsDir(fix.dataDir, version.Current)
	err := os.MkdirAll(toolsDir, 0755)
	c.Assert(err, gc.IsNil)
	jujudPath := filepath.Join(toolsDir, "jujud")
	err = ioutil.WriteFile(jujudPath, []byte(fakeJujud), 0755)
	c.Assert(err, gc.IsNil)
	toolsPath := filepath.Join(toolsDir, "downloaded-tools.txt")
	testTools := coretools.Tools{Version: version.Current, URL: "http://testing.invalid/tools"}
	data, err := json.Marshal(testTools)
	c.Assert(err, gc.IsNil)
	err = ioutil.WriteFile(toolsPath, data, 0644)
	c.Assert(err, gc.IsNil)
	fix.binDir = c.MkDir()
	fix.origPath = os.Getenv("PATH")
	os.Setenv("PATH", fix.binDir+":"+fix.origPath)
	fix.makeBin(c, "status", `echo "blah stop/waiting"`)
	fix.makeBin(c, "stopped-status", `echo "blah stop/waiting"`)
	fix.makeBin(c, "started-status", `echo "blah start/running, process 666"`)
	fix.makeBin(c, "start", "cp $(which started-status) $(which status)")
	fix.makeBin(c, "stop", "cp $(which stopped-status) $(which status)")
}
Example #2
0
func TestUnionFsDropCache(t *testing.T) {
	wd, clean := setupUfs(t)
	defer clean()

	err := ioutil.WriteFile(wd+"/ro/file", []byte("bla"), 0644)
	CheckSuccess(err)

	_, err = os.Lstat(wd + "/mnt/.drop_cache")
	CheckSuccess(err)

	names, err := Readdirnames(wd + "/mnt")
	CheckSuccess(err)
	if len(names) != 1 || names[0] != "file" {
		t.Fatal("unexpected names", names)
	}

	err = ioutil.WriteFile(wd+"/ro/file2", []byte("blabla"), 0644)
	names2, err := Readdirnames(wd + "/mnt")
	CheckSuccess(err)
	if len(names2) != len(names) {
		t.Fatal("mismatch", names2)
	}

	err = ioutil.WriteFile(wd+"/mnt/.drop_cache", []byte("does not matter"), 0644)
	CheckSuccess(err)
	names2, err = Readdirnames(wd + "/mnt")
	if len(names2) != 2 {
		t.Fatal("mismatch 2", names2)
	}
}
Example #3
0
func (s *charmsSuite) TestGetUsesCache(c *gc.C) {
	// Add a fake charm archive in the cache directory.
	cacheDir := filepath.Join(s.DataDir(), "charm-get-cache")
	err := os.MkdirAll(cacheDir, 0755)
	c.Assert(err, jc.ErrorIsNil)

	// Create and save a bundle in it.
	charmDir := testcharms.Repo.ClonedDir(c.MkDir(), "dummy")
	testPath := filepath.Join(charmDir.Path, "utils.js")
	contents := "// blah blah"
	err = ioutil.WriteFile(testPath, []byte(contents), 0755)
	c.Assert(err, jc.ErrorIsNil)
	var buffer bytes.Buffer
	err = charmDir.ArchiveTo(&buffer)
	c.Assert(err, jc.ErrorIsNil)
	charmArchivePath := filepath.Join(
		cacheDir, charm.Quote("local:trusty/django-42")+".zip")
	err = ioutil.WriteFile(charmArchivePath, buffer.Bytes(), 0644)
	c.Assert(err, jc.ErrorIsNil)

	// Ensure the cached contents are properly retrieved.
	uri := s.charmsURI(c, "?url=local:trusty/django-42&file=utils.js")
	resp, err := s.authRequest(c, "GET", uri, "", nil)
	c.Assert(err, jc.ErrorIsNil)
	s.assertGetFileResponse(c, resp, contents, "application/javascript")
}
Example #4
0
func (m *Master) generateSSHKey(user, privateKeyfile, publicKeyfile string) error {
	private, public, err := util.GenerateKey(2048)
	if err != nil {
		return err
	}
	// If private keyfile already exists, we must have only made it halfway
	// through last time, so delete it.
	exists, err := util.FileExists(privateKeyfile)
	if err != nil {
		glog.Errorf("Error detecting if private key exists: %v", err)
	} else if exists {
		glog.Infof("Private key exists, but public key does not")
		if err := os.Remove(privateKeyfile); err != nil {
			glog.Errorf("Failed to remove stale private key: %v", err)
		}
	}
	if err := ioutil.WriteFile(privateKeyfile, util.EncodePrivateKey(private), 0600); err != nil {
		return err
	}
	publicKeyBytes, err := util.EncodePublicKey(public)
	if err != nil {
		return err
	}
	if err := ioutil.WriteFile(publicKeyfile+".tmp", publicKeyBytes, 0600); err != nil {
		return err
	}
	return os.Rename(publicKeyfile+".tmp", publicKeyfile)
}
Example #5
0
func calculateLayerChecksum(graphDir, id string, ls checksumCalculator) error {
	diffIDFile := filepath.Join(graphDir, id, migrationDiffIDFileName)
	if _, err := os.Lstat(diffIDFile); err == nil {
		return nil
	} else if !os.IsNotExist(err) {
		return err
	}

	parent, err := getParent(filepath.Join(graphDir, id))
	if err != nil {
		return err
	}

	diffID, size, err := ls.ChecksumForGraphID(id, parent, filepath.Join(graphDir, id, tarDataFileName), filepath.Join(graphDir, id, migrationTarDataFileName))
	if err != nil {
		return err
	}

	if err := ioutil.WriteFile(filepath.Join(graphDir, id, migrationSizeFileName), []byte(strconv.Itoa(int(size))), 0600); err != nil {
		return err
	}

	tmpFile := filepath.Join(graphDir, id, migrationDiffIDFileName+".tmp")
	if err := ioutil.WriteFile(tmpFile, []byte(diffID), 0600); err != nil {
		return err
	}

	if err := os.Rename(tmpFile, filepath.Join(graphDir, id, migrationDiffIDFileName)); err != nil {
		return err
	}

	logrus.Infof("calculated checksum for layer %s: %s", id, diffID)
	return nil
}
Example #6
0
func TestReadConfigPaths_dir(t *testing.T) {
	td, err := ioutil.TempDir("", "consul")
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.RemoveAll(td)

	err = ioutil.WriteFile(filepath.Join(td, "a.json"),
		[]byte(`{"node_name": "bar"}`), 0644)
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	err = ioutil.WriteFile(filepath.Join(td, "b.json"),
		[]byte(`{"node_name": "baz"}`), 0644)
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	// A non-json file, shouldn't be read
	err = ioutil.WriteFile(filepath.Join(td, "c"),
		[]byte(`{"node_name": "bad"}`), 0644)
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	config, err := ReadConfigPaths([]string{td})
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	if config.NodeName != "baz" {
		t.Fatalf("bad: %#v", config)
	}
}
Example #7
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)
}
Example #8
0
func TestOverwriteRename(t *testing.T) {
	tc := NewTestCase(t)
	defer tc.Cleanup()

	t.Log("Testing rename overwrite.")

	sd := tc.mnt + "/testOverwriteRename"
	err := os.MkdirAll(sd, 0755)
	if err != nil {
		t.Fatalf("MkdirAll failed: %v", err)
	}

	d := sd + "/dest"
	err = ioutil.WriteFile(d, []byte("blabla"), 0644)
	if err != nil {
		t.Fatalf("WriteFile failed: %v", err)
	}

	s := sd + "/src"
	err = ioutil.WriteFile(s, []byte("blabla"), 0644)
	if err != nil {
		t.Fatalf("WriteFile failed: %v", err)
	}

	err = os.Rename(s, d)
	if err != nil {
		t.Fatalf("Rename failed: %v", err)
	}
}
Example #9
0
func NewConfig() *Config {
	var runControllerScript string = `
sshd_run=$(which sshd)
$sshd_run -D&

munged_run=$(which munged)
$munged_run -F&

slurm_env_config_run=$(which 'slurm-env-config')
$slurm_env_config_run >> /etc/slurm.conf

slurmctl_run=$(which /usr/sbin/slurmctld)
$slurmctl_run -D -v&
wait
`

	var runNodeScript string = `
sshd_run=$(which sshd)
$sshd_run -D&

munged_run=$(which munged)
$munged_run -F&

slurm_env_config_run=$(which 'slurm-env-config')
$slurm_env_config_run >> /etc/slurm.conf

slurmctl_run=$(which /usr/sbin/slurmd)
$slurmctl_run -D -v&
wait
`
	config := &Config{
		CLI: newCli(),
		Dir: newConfDir(),
	}

	controllerScriptPath := filepath.Join(config.Dir, "run_controller.sh")
	err := ioutil.WriteFile(controllerScriptPath, []byte(runControllerScript), 0755)
	if err != nil {
		log.Fatal("failed to write run_controller.sh: ", err)
	}

	nodeScriptPath := filepath.Join(config.Dir, "run_node.sh")
	err = ioutil.WriteFile(nodeScriptPath, []byte(runNodeScript), 0755)
	if err != nil {
		log.Fatal("failed to write run_node.sh: ", err)
	}

	u, err := user.Current()
	if err != nil {
		log.Fatal("failed to get current user: "******"failed to get current working directory: ", err)
	}
	return config
}
Example #10
0
// Flaky test, due to rename race condition.
func TestDelRename(t *testing.T) {
	tc := NewTestCase(t)
	defer tc.Cleanup()

	t.Log("Testing del+rename.")

	sd := tc.mnt + "/testDelRename"
	err := os.MkdirAll(sd, 0755)
	CheckSuccess(err)

	d := sd + "/dest"
	err = ioutil.WriteFile(d, []byte("blabla"), 0644)
	CheckSuccess(err)

	f, err := os.Open(d)
	CheckSuccess(err)
	defer f.Close()

	err = os.Remove(d)
	CheckSuccess(err)

	s := sd + "/src"
	err = ioutil.WriteFile(s, []byte("blabla"), 0644)
	CheckSuccess(err)

	err = os.Rename(s, d)
	CheckSuccess(err)
}
Example #11
0
func TestUninstall(t *testing.T) {
	fakeSB := runit.FakeServiceBuilder()
	defer fakeSB.Cleanup()
	serviceBuilder := &fakeSB.ServiceBuilder

	testPodDir, err := ioutil.TempDir("", "testPodDir")
	Assert(t).IsNil(err, "Got an unexpected error creating a temp directory")
	pod := Pod{
		Id:             "testPod",
		path:           testPodDir,
		ServiceBuilder: serviceBuilder,
	}
	manifest := getTestPodManifest(t)
	manifestContent, err := manifest.Marshal()
	Assert(t).IsNil(err, "couldn't get manifest bytes")
	err = ioutil.WriteFile(pod.currentPodManifestPath(), manifestContent, 0744)
	Assert(t).IsNil(err, "should have written current manifest")

	serviceBuilderFilePath := filepath.Join(serviceBuilder.ConfigRoot, "testPod.yaml")
	err = ioutil.WriteFile(serviceBuilderFilePath, []byte("stuff"), 0744)
	Assert(t).IsNil(err, "Error writing fake servicebuilder file")

	err = pod.Uninstall()
	Assert(t).IsNil(err, "Error uninstalling pod")
	_, err = os.Stat(serviceBuilderFilePath)
	Assert(t).IsTrue(os.IsNotExist(err), "Expected file to not exist after uninstall")
	_, err = os.Stat(pod.currentPodManifestPath())
	Assert(t).IsTrue(os.IsNotExist(err), "Expected file to not exist after uninstall")
}
Example #12
0
// PatchExecutable creates an executable called 'execName' in a new test
// directory and that directory is added to the path.
func PatchExecutable(c *gc.C, patcher CleanupPatcher, execName, script string, exitCodes ...int) {
	dir := c.MkDir()
	patcher.PatchEnvironment("PATH", joinPathLists(dir, os.Getenv("PATH")))
	var filename string
	switch runtime.GOOS {
	case "windows":
		filename = filepath.Join(dir, execName+".bat")
	default:
		filename = filepath.Join(dir, execName)
	}
	os.Remove(filename + ".out")
	err := ioutil.WriteFile(filename, []byte(script), 0755)
	c.Assert(err, gc.IsNil)

	if len(exitCodes) > 0 {
		filename = execName + ".exitcodes"
		codes := make([]string, len(exitCodes))
		for i, code := range exitCodes {
			codes[i] = strconv.Itoa(code)
		}
		s := strings.Join(codes, ";") + ";"
		err = ioutil.WriteFile(filename, []byte(s), 0644)
		c.Assert(err, gc.IsNil)
		patcher.AddCleanup(func(*gc.C) {
			os.Remove(filename)
		})
	}
}
Example #13
0
func (fix *SimpleToolsFixture) SetUp(c *gc.C, dataDir string) {
	fix.dataDir = dataDir
	fix.logDir = c.MkDir()
	current := version.Binary{
		Number: version.Current,
		Arch:   arch.HostArch(),
		Series: series.HostSeries(),
	}
	toolsDir := tools.SharedToolsDir(fix.dataDir, current)
	err := os.MkdirAll(toolsDir, 0755)
	c.Assert(err, jc.ErrorIsNil)
	jujudPath := filepath.Join(toolsDir, "jujud")
	err = ioutil.WriteFile(jujudPath, []byte(fakeJujud), 0755)
	c.Assert(err, jc.ErrorIsNil)
	toolsPath := filepath.Join(toolsDir, "downloaded-tools.txt")
	testTools := coretools.Tools{Version: current, URL: "http://testing.invalid/tools"}
	data, err := json.Marshal(testTools)
	c.Assert(err, jc.ErrorIsNil)
	err = ioutil.WriteFile(toolsPath, data, 0644)
	c.Assert(err, jc.ErrorIsNil)
	fix.binDir = c.MkDir()
	fix.origPath = os.Getenv("PATH")
	os.Setenv("PATH", fix.binDir+":"+fix.origPath)
	fix.makeBin(c, "status", `echo "blah stop/waiting"`)
	fix.makeBin(c, "stopped-status", `echo "blah stop/waiting"`)
	fix.makeBin(c, "started-status", `echo "blah start/running, process 666"`)
	fix.makeBin(c, "start", "cp $(which started-status) $(which status)")
	fix.makeBin(c, "stop", "cp $(which stopped-status) $(which status)")

	fix.data = svctesting.NewFakeServiceData()
}
Example #14
0
func materialize(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {

	log.Println("[materialize]")

	rq := new(protocol.NetworkMaterializationRequest)
	err := protocol.Unpack(r.Body, rq)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		w.Header().Set("Content-Type", "application/json")
		d := protocol.Diagnostic{"error", "malformed json"}
		w.Write(protocol.PackWire(d))
		return
	}

	err, em := embed(&rq.Net, rq.Mapper)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		w.Header().Set("Content-Type", "application/json")
		d := protocol.Diagnostic{"error", fmt.Sprintf("materialization: %s", err)}
		w.Write(protocol.PackWire(d))
		return
	}

	xpdir := "/marina/xp/" + rq.Net.Name
	os.MkdirAll(xpdir, 0755)
	ioutil.WriteFile(xpdir+"/net.json", protocol.PackLegible(rq.Net), 0644)
	ioutil.WriteFile(xpdir+"/map.json", protocol.PackLegible(em), 0644)

}
Example #15
0
// Copy existing index configuration to backup, then save the latest index configuration.
func (col *Col) BackupAndSaveConf() error {
	if col.Config == nil {
		return nil
	}
	// Read existing file content and copy to backup
	oldConfig, err := ioutil.ReadFile(col.ConfigFileName)
	if err != nil {
		return err
	}
	if err = ioutil.WriteFile(col.ConfBackupFileName, []byte(oldConfig), 0600); err != nil {
		return err
	}
	if col.Config == nil {
		return nil
	}
	// Marshal index configuration into file
	newConfig, err := json.Marshal(col.Config)
	if err != nil {
		return err
	}
	if err = ioutil.WriteFile(col.ConfigFileName, newConfig, 0600); err != nil {
		return err
	}
	return nil
}
Example #16
0
func TestTarWithOptions(t *testing.T) {
	origin, err := ioutil.TempDir("", "docker-test-untar-origin")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(origin)
	if err := ioutil.WriteFile(path.Join(origin, "1"), []byte("hello world"), 0700); err != nil {
		t.Fatal(err)
	}
	if err := ioutil.WriteFile(path.Join(origin, "2"), []byte("welcome!"), 0700); err != nil {
		t.Fatal(err)
	}

	cases := []struct {
		opts       *TarOptions
		numChanges int
	}{
		{&TarOptions{Includes: []string{"1"}}, 1},
		{&TarOptions{Excludes: []string{"2"}}, 1},
	}
	for _, testCase := range cases {
		changes, err := tarUntar(t, origin, testCase.opts)
		if err != nil {
			t.Fatalf("Error tar/untar when testing inclusion/exclusion: %s", err)
		}
		if len(changes) != testCase.numChanges {
			t.Errorf("Expected %d changes, got %d for %+v:",
				testCase.numChanges, len(changes), testCase.opts)
		}
	}
}
Example #17
0
func (s *S) TestReloading(c *C) {
	rlName := "reloading.neste"
	rlPath := path.Join(baseDir, rlName)
	data := "foo"
	st := []byte("starting template: {@}\n")
	mt := []byte("modified template: {@}\n")
	sExpected := "starting template: foo\n"
	mExpected := "modified template: foo\n"

	ioutil.WriteFile(rlPath, st, 0644)
	tm := New(baseDir, nil)
	c.Assert(tm.reloading, Equals, false)
	t := tm.MustAddFile(rlName)

	output, err := t.Render(data)
	c.Assert(err, IsNil)
	c.Assert(output, Equals, sExpected)

	// Write changes
	ioutil.WriteFile(rlPath, mt, 0644)
	tm.SetReloading(true)

	// Attempt to force mtime to change.
	err = os.Chtimes(rlPath, time.Nanoseconds(), time.Nanoseconds())
	c.Assert(err, IsNil)

	output, err = t.Render(data)
	c.Assert(err, IsNil)
	c.Assert(output, Equals, mExpected)
}
Example #18
0
func (m *Monitor) updateCgroups(id string, env map[string]string) {
	if env["SWAP"] == "1" {
		bytes := "18446744073709551615"

		fmt.Fprintf(os.Stderr, "id=%s cgroup=memory.memsw.limit_in_bytes value=%s\n", id, bytes)
		err := ioutil.WriteFile(fmt.Sprintf("/cgroup/memory/docker/%s/memory.memsw.limit_in_bytes", id), []byte(bytes), 0644)

		if err != nil {
			fmt.Fprintf(os.Stderr, "error: %s\n", err)
		}

		fmt.Fprintf(os.Stderr, "id=%s cgroup=memory.soft_limit_in_bytes value=%s\n", id, bytes)
		err = ioutil.WriteFile(fmt.Sprintf("/cgroup/memory/docker/%s/memory.soft_limit_in_bytes", id), []byte(bytes), 0644)

		if err != nil {
			fmt.Fprintf(os.Stderr, "error: %s\n", err)
		}

		fmt.Fprintf(os.Stderr, "id=%s cgroup=memory.limit_in_bytes value=%s\n", id, bytes)
		err = ioutil.WriteFile(fmt.Sprintf("/cgroup/memory/docker/%s/memory.limit_in_bytes", id), []byte(bytes), 0644)

		if err != nil {
			fmt.Fprintf(os.Stderr, "error: %s\n", err)
		}
	}
}
Example #19
0
func checkstatus(p *os.Process, pname string, timest string) bool {
	fmt.Println("checkstatus", pname, p)
	reportlog[timest]["status"] = pname + " running"
	reportlog[timest][pname+"start"] = time.Now().Format("20060102150405")
	liner, _ := json.Marshal(reportlog)
	ioutil.WriteFile("static/data/reportlog.json", liner, 0)
	pw, _ := p.Wait()
	fmt.Println("checkstatus over", p)
	fmt.Println("timest=", timest)
	reportlog[timest][pname+"stop"] = time.Now().Format("20060102150405")
	t1, _ := time.Parse("20060102150405", reportlog[timest][pname+"stop"])
	t2, _ := time.Parse("20060102150405", reportlog[timest][pname+"start"])
	reportlog[timest][pname+"time"] = strconv.Itoa(int(t1.Sub(t2)) / 1e9)
	fmt.Println("t1=", t1)
	fmt.Println("t2=", t2)
	fmt.Println("cost=", t1.Sub(t2))
	status := pw.Success()
	if status == true {
		reportlog[timest]["status"] = pname + " success"
		fmt.Println("checkstatus over success ", pname, p)
	} else {
		reportlog[timest]["status"] = pname + " failed"
		fmt.Println("checkstatus over failed ", pname, p)
	}
	liner, _ = json.Marshal(reportlog)
	ioutil.WriteFile("static/data/reportlog.json", liner, 0)
	return status

}
Example #20
0
func (s *UpgradeCharmSuccessSuite) TestSwitch(c *gc.C) {
	myriakPath := testing.Charms.RenamedClonedDirPath(s.SeriesPath, "riak", "myriak")
	err := ioutil.WriteFile(path.Join(myriakPath, "metadata.yaml"), myriakMeta, 0644)
	c.Assert(err, gc.IsNil)

	// Test with local repo and no explicit revsion.
	err = runUpgradeCharm(c, "riak", "--switch=local:myriak")
	c.Assert(err, gc.IsNil)
	curl := s.assertUpgraded(c, 7, false)
	c.Assert(curl.String(), gc.Equals, "local:precise/myriak-7")
	s.assertLocalRevision(c, 7, myriakPath)

	// Now try the same with explicit revision - should fail.
	err = runUpgradeCharm(c, "riak", "--switch=local:myriak-7")
	c.Assert(err, gc.ErrorMatches, `already running specified charm "local:precise/myriak-7"`)

	// Change the revision to 42 and upgrade to it with explicit revision.
	err = ioutil.WriteFile(path.Join(myriakPath, "revision"), []byte("42"), 0644)
	c.Assert(err, gc.IsNil)
	err = runUpgradeCharm(c, "riak", "--switch=local:myriak-42")
	c.Assert(err, gc.IsNil)
	curl = s.assertUpgraded(c, 42, false)
	c.Assert(curl.String(), gc.Equals, "local:precise/myriak-42")
	s.assertLocalRevision(c, 42, myriakPath)
}
Example #21
0
func (this *MixMatch) Regenerate() {
	fmt.Printf("mixbench\n")
	uuidData, err := ioutil.ReadFile("../uuid.go")
	if err != nil {
		panic(err)
	}
	if err := ioutil.WriteFile("./testdata/uuid.go", uuidData, 0666); err != nil {
		panic(err)
	}
	data, err := ioutil.ReadFile("../thetest.proto")
	if err != nil {
		panic(err)
	}
	content := string(data)
	for i, old := range this.Old {
		content = strings.Replace(content, old, this.New[i], -1)
	}
	if err := ioutil.WriteFile("./testdata/thetest.proto", []byte(content), 0666); err != nil {
		panic(err)
	}
	var regenerate = exec.Command("protoc", "--dgo_out=.", "-I="+config.ProtoPath, "./testdata/thetest.proto")
	fmt.Printf("regenerating\n")
	out, err := regenerate.CombinedOutput()
	fmt.Printf("regenerate output: %v\n", string(out))
	if err != nil {
		panic(err)
	}
}
Example #22
0
func TestTarUntar(t *testing.T) {
	origin, err := ioutil.TempDir("", "docker-test-untar-origin")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(origin)
	if err := ioutil.WriteFile(path.Join(origin, "1"), []byte("hello world"), 0700); err != nil {
		t.Fatal(err)
	}
	if err := ioutil.WriteFile(path.Join(origin, "2"), []byte("welcome!"), 0700); err != nil {
		t.Fatal(err)
	}
	if err := ioutil.WriteFile(path.Join(origin, "3"), []byte("will be ignored"), 0700); err != nil {
		t.Fatal(err)
	}

	for _, c := range []Compression{
		Uncompressed,
		Gzip,
	} {
		changes, err := tarUntar(t, origin, &TarOptions{
			Compression:     c,
			ExcludePatterns: []string{"3"},
		})

		if err != nil {
			t.Fatalf("Error tar/untar for compression %s: %s", c.Extension(), err)
		}

		if len(changes) != 1 || changes[0].Path != "/3" {
			t.Fatalf("Unexpected differences after tarUntar: %v", changes)
		}
	}
}
Example #23
0
func InitDiffFile() error {
	file1Data := "3"
	file2Data := "2"
	file3Data := "1"

	if err := os.MkdirAll(path.Join(diffTempDir, "1"), 0755); err != nil {
		return err
	}
	if err := os.MkdirAll(path.Join(diffTempDir, "2"), 0755); err != nil {
		return err
	}
	if err := os.MkdirAll(path.Join(diffTempDir, "3"), 0755); err != nil {
		return err
	}
	if err := ioutil.WriteFile(path.Join(diffTempDir, "1")+"/1", []byte(file1Data), 0755); err != nil {
		return err
	}
	if err := ioutil.WriteFile(path.Join(diffTempDir, "2")+"/2", []byte(file2Data), 0755); err != nil {
		return err
	}
	if err := ioutil.WriteFile(path.Join(diffTempDir, "3")+"/3", []byte(file3Data), 0755); err != nil {
		return err
	}

	return nil
}
Example #24
0
// saveCertResource saves the certificate resource to disk. This
// includes the certificate file itself, the private key, and the
// metadata file.
func saveCertResource(cert acme.CertificateResource) error {
	err := os.MkdirAll(storage.Site(cert.Domain), 0700)
	if err != nil {
		return err
	}

	// Save cert
	err = ioutil.WriteFile(storage.SiteCertFile(cert.Domain), cert.Certificate, 0600)
	if err != nil {
		return err
	}

	// Save private key
	err = ioutil.WriteFile(storage.SiteKeyFile(cert.Domain), cert.PrivateKey, 0600)
	if err != nil {
		return err
	}

	// Save cert metadata
	jsonBytes, err := json.MarshalIndent(&cert, "", "\t")
	if err != nil {
		return err
	}
	err = ioutil.WriteFile(storage.SiteMetaFile(cert.Domain), jsonBytes, 0600)
	if err != nil {
		return err
	}

	return nil
}
Example #25
0
func (ca *CA) MakeClientCertificate(certFile, keyFile string, u user.Info) (*TLSCertificateConfig, error) {
	glog.V(4).Infof("Generating client cert in %s and key in %s", certFile, keyFile)
	// ensure parent dirs
	if err := os.MkdirAll(filepath.Dir(certFile), os.FileMode(0755)); err != nil {
		return nil, err
	}
	if err := os.MkdirAll(filepath.Dir(keyFile), os.FileMode(0755)); err != nil {
		return nil, err
	}

	clientPublicKey, clientPrivateKey, _ := NewKeyPair()
	clientTemplate, _ := newClientCertificateTemplate(x509request.UserToSubject(u))
	clientCrt, _ := ca.signCertificate(clientTemplate, clientPublicKey)

	certData, err := encodeCertificates(clientCrt)
	if err != nil {
		return nil, err
	}
	keyData, err := encodeKey(clientPrivateKey)
	if err != nil {
		return nil, err
	}

	if err = ioutil.WriteFile(certFile, certData, os.FileMode(0644)); err != nil {
		return nil, err
	}
	if err = ioutil.WriteFile(keyFile, keyData, os.FileMode(0600)); err != nil {
		return nil, err
	}

	return GetTLSCertificateConfig(certFile, keyFile)
}
Example #26
0
func (daemon *Daemon) initCgroupsPath(path string) error {
	if path == "/" || path == "." {
		return nil
	}

	daemon.initCgroupsPath(filepath.Dir(path))

	_, root, err := cgroups.FindCgroupMountpointAndRoot("cpu")
	if err != nil {
		return err
	}

	path = filepath.Join(root, path)
	sysinfo := sysinfo.New(false)
	if err := os.MkdirAll(path, 0755); err != nil && !os.IsExist(err) {
		return err
	}
	if sysinfo.CPURealtimePeriod && daemon.configStore.CPURealtimePeriod != 0 {
		if err := ioutil.WriteFile(filepath.Join(path, "cpu.rt_period_us"), []byte(strconv.FormatInt(daemon.configStore.CPURealtimePeriod, 10)), 0700); err != nil {
			return err
		}
	}
	if sysinfo.CPURealtimeRuntime && daemon.configStore.CPURealtimeRuntime != 0 {
		if err := ioutil.WriteFile(filepath.Join(path, "cpu.rt_runtime_us"), []byte(strconv.FormatInt(daemon.configStore.CPURealtimeRuntime, 10)), 0700); err != nil {
			return err
		}
	}

	return nil
}
Example #27
0
// storeImage stores file system layer data for the given image to the
// graph's storage driver. Image metadata is stored in a file
// at the specified root directory.
func (graph *Graph) storeImage(id, parent string, config []byte, layerData io.Reader, root string) (err error) {
	var size int64
	// Store the layer. If layerData is not nil, unpack it into the new layer
	if layerData != nil {
		if size, err = graph.disassembleAndApplyTarLayer(id, parent, layerData, root); err != nil {
			return err
		}
	}

	if err := graph.saveSize(root, size); err != nil {
		return err
	}

	if err := ioutil.WriteFile(jsonPath(root), config, 0600); err != nil {
		return err
	}

	// If image is pointing to a parent via CompatibilityID write the reference to disk
	img, err := image.NewImgJSON(config)
	if err != nil {
		return err
	}

	if img.ParentID.Validate() == nil && parent != img.ParentID.Hex() {
		if err := ioutil.WriteFile(filepath.Join(root, parentFileName), []byte(parent), 0600); err != nil {
			return err
		}
	}
	return nil
}
Example #28
0
func TestLookupOK(t *testing.T) {
	tmpFolder, err := ioutil.TempDir("", "lookup-tests")
	if err != nil {
		t.Fatal(err)
	}
	tmpFile1 := filepath.Join(tmpFolder, "file1")
	tmpFile2 := filepath.Join(tmpFolder, "file2")
	if err = ioutil.WriteFile(tmpFile1, []byte("content1"), 0755); err != nil {
		t.Fatal(err)
	}
	if err = ioutil.WriteFile(tmpFile2, []byte("content2"), 0755); err != nil {
		t.Fatal(err)
	}

	fileConfigLookup := FileResourceLookup{}

	valids := map[input]string{
		input{"file1", tmpFolder + "/"}:     "content1",
		input{"file2", tmpFolder + "/"}:     "content2",
		input{tmpFile1, tmpFolder}:          "content1",
		input{tmpFile1, "/does/not/exists"}: "content1",
		input{"file2", tmpFile1}:            "content2",
	}

	for valid, expectedContent := range valids {
		out, _, err := fileConfigLookup.Lookup(valid.file, valid.relativeTo)
		if err != nil || string(out) != expectedContent {
			t.Fatalf("Expected %s to contains '%s', got %s, %v.", valid.file, expectedContent, out, err)
		}
	}
}
Example #29
0
func CopyImgLayer(srcPath, srcFile, dstPath, dstFile string, reqbody []byte) (int, error) {
	if !utils.IsDirExist(dstPath) {
		os.MkdirAll(dstPath, os.ModePerm)
	}

	if utils.IsFileExist(dstFile) {
		os.Remove(dstFile)
	}

	var data []byte
	if _, err := os.Stat(srcFile); err == nil {
		data, _ = ioutil.ReadFile(srcFile)
		if err := ioutil.WriteFile(dstFile, data, 0777); err != nil {
			return 0, err
		}
		os.RemoveAll(srcPath)
	} else {
		data = reqbody
		if err := ioutil.WriteFile(dstFile, data, 0777); err != nil {
			return 0, err
		}
	}

	return len(data), nil
}
Example #30
0
func TestPacket(t *testing.T) {
	tests := []struct {
		path string
		data string
	}{
		{
			"testdata/Vintage/Vintageous.sublime-settings",
			"Testing packages",
		},
	}
	for i, test := range tests {
		s := NewPacket(test.path, nil)
		d, err := ioutil.ReadFile(test.path)
		if err != nil {
			t.Fatalf("Test %d: Can't read file: %s", i, err)
		}
		if d1 := s.Get().([]byte); string(d) != string(d1) {
			t.Errorf("Test %d: Expected %v but, got %s", i, d, string(d1))
		}
		if err := ioutil.WriteFile(test.path, []byte(test.data), 0644); err != nil {
			t.Fatalf("Test %d: Can't write file: %s", i, err)
		}
		s.Load()
		if d1 := s.Get().([]byte); test.data != string(d1) {
			t.Errorf("Test %d: Expected %s but, got %s", i, test.data, string(d1))
		}
		if err := ioutil.WriteFile(test.path, d, 0644); err != nil {
			t.Fatalf("Test %d: Can't write back file: %s", i, err)
		}
	}
}