func BenchmarkTarUntarWithLinks(b *testing.B) { origin, err := ioutil.TempDir("", "docker-test-untar-origin") if err != nil { b.Fatal(err) } tempDir, err := ioutil.TempDir("", "docker-test-untar-destination") if err != nil { b.Fatal(err) } target := filepath.Join(tempDir, "dest") n, err := prepareUntarSourceDirectory(100, origin, true) if err != nil { b.Fatal(err) } defer os.RemoveAll(origin) defer os.RemoveAll(tempDir) b.ResetTimer() b.SetBytes(int64(n)) for n := 0; n < b.N; n++ { err := TarUntar(origin, target) if err != nil { b.Fatal(err) } os.RemoveAll(target) } }
func TestProvisionerPrepare_cookbookPaths(t *testing.T) { var p Provisioner path1, err := ioutil.TempDir("", "cookbooks_one") if err != nil { t.Fatalf("err: %s", err) } path2, err := ioutil.TempDir("", "cookbooks_two") if err != nil { t.Fatalf("err: %s", err) } defer os.Remove(path1) defer os.Remove(path2) config := testConfig() config["cookbook_paths"] = []string{path1, path2} err = p.Prepare(config) if err != nil { t.Fatalf("err: %s", err) } if len(p.config.CookbookPaths) != 2 { t.Fatalf("unexpected: %#v", p.config.CookbookPaths) } if p.config.CookbookPaths[0] != path1 || p.config.CookbookPaths[1] != path2 { t.Fatalf("unexpected: %#v", p.config.CookbookPaths) } }
func (s *MyAPIFSCacheSuite) SetUpSuite(c *C) { root, err := ioutil.TempDir(os.TempDir(), "api-") c.Assert(err, IsNil) s.root = root fsroot, err := ioutil.TempDir(os.TempDir(), "api-") c.Assert(err, IsNil) fs.SetFSMultipartsConfigPath(filepath.Join(root, "multiparts.json")) multiparts := &fs.Multiparts{} multiparts.ActiveSession = make(map[string]*fs.MultipartSession) perr := fs.SaveMultipartsSession(multiparts) c.Assert(perr, IsNil) accessKeyID, perr := generateAccessKeyID() c.Assert(perr, IsNil) secretAccessKey, perr := generateSecretAccessKey() c.Assert(perr, IsNil) authConf := &AuthConfig{} authConf.AccessKeyID = string(accessKeyID) authConf.SecretAccessKey = string(secretAccessKey) s.accessKeyID = string(accessKeyID) s.secretAccessKey = string(secretAccessKey) // do this only once here customConfigPath = root perr = saveAuthConfig(authConf) c.Assert(perr, IsNil) minioAPI := getNewAPI(fsroot, false) httpHandler := getAPIHandler(false, minioAPI) testAPIFSCacheServer = httptest.NewServer(httpHandler) }
// SetupHostPathVolumes will create multiple PersistentVolumes with given capacity func SetupHostPathVolumes(c kclient.PersistentVolumeInterface, prefix, capacity string, count int) (volumes []*kapi.PersistentVolume, err error) { rootDir, err := ioutil.TempDir(TestContext.OutputDir, "persistent-volumes") if err != nil { return volumes, err } for i := 0; i < count; i++ { dir, err := ioutil.TempDir(rootDir, fmt.Sprintf("%0.4d", i)) if err != nil { return volumes, err } if _, err = exec.LookPath("chcon"); err != nil { err := exec.Command("chcon", "-t", "svirt_sandbox_file_t", dir).Run() if err != nil { return volumes, err } } if err = os.Chmod(dir, 0777); err != nil { return volumes, err } pv, err := c.Create(CreatePersistentVolume(fmt.Sprintf("%s%s-%0.4d", pvPrefix, prefix, i), capacity, dir)) if err != nil { return volumes, err } volumes = append(volumes, pv) } return volumes, err }
func TestFileSS_CreateSnapshotMissingParentDir(t *testing.T) { parent, err := ioutil.TempDir("", "raft") if err != nil { t.Fatalf("err: %v ", err) } defer os.RemoveAll(parent) dir, err := ioutil.TempDir(parent, "raft") if err != nil { t.Fatalf("err: %v ", err) } snap, err := NewFileSnapshotStore(dir, 3, nil) if err != nil { t.Fatalf("err: %v", err) } os.RemoveAll(parent) peers := []byte("all my lovely friends") _, err = snap.Create(10, 3, peers) if err != nil { t.Fatalf("should not fail when using non existing parent") } }
func (s *TestSuite) TestDiffObjects(c *C) { /// filesystem root1, err := ioutil.TempDir(os.TempDir(), "cmd-") c.Assert(err, IsNil) defer os.RemoveAll(root1) root2, err := ioutil.TempDir(os.TempDir(), "cmd-") c.Assert(err, IsNil) defer os.RemoveAll(root2) objectPath1 := filepath.Join(root1, "object1") data := "hello" dataLen := len(data) perr := putTarget(objectPath1, int64(dataLen), bytes.NewReader([]byte(data))) c.Assert(perr, IsNil) objectPath2 := filepath.Join(root2, "object1") data = "hello" dataLen = len(data) perr = putTarget(objectPath2, int64(dataLen), bytes.NewReader([]byte(data))) c.Assert(perr, IsNil) for diff := range doDiffMain(objectPath1, objectPath2, false) { c.Assert(diff.Error, IsNil) } }
// init is used to initialize the client and perform any setup // needed before we begin starting its various components. func (c *Client) init() error { // Ensure the state dir exists if we have one if c.config.StateDir != "" { if err := os.MkdirAll(c.config.StateDir, 0700); err != nil { return fmt.Errorf("failed creating state dir: %s", err) } } else { // Othewise make a temp directory to use. p, err := ioutil.TempDir("", "NomadClient") if err != nil { return fmt.Errorf("failed creating temporary directory for the StateDir: %v", err) } c.config.StateDir = p } c.logger.Printf("[INFO] client: using state directory %v", c.config.StateDir) // Ensure the alloc dir exists if we have one if c.config.AllocDir != "" { if err := os.MkdirAll(c.config.AllocDir, 0755); err != nil { return fmt.Errorf("failed creating alloc dir: %s", err) } } else { // Othewise make a temp directory to use. p, err := ioutil.TempDir("", "NomadClient") if err != nil { return fmt.Errorf("failed creating temporary directory for the AllocDir: %v", err) } c.config.AllocDir = p } c.logger.Printf("[INFO] client: using alloc directory %v", c.config.AllocDir) return nil }
func (s *MyAPIFSCacheSuite) SetUpSuite(c *C) { root, e := ioutil.TempDir(os.TempDir(), "api-") c.Assert(e, IsNil) s.root = root fsroot, e := ioutil.TempDir(os.TempDir(), "api-") c.Assert(e, IsNil) accessKeyID, err := generateAccessKeyID() c.Assert(err, IsNil) secretAccessKey, err := generateSecretAccessKey() c.Assert(err, IsNil) conf := newConfigV2() conf.Credentials.AccessKeyID = string(accessKeyID) conf.Credentials.SecretAccessKey = string(secretAccessKey) s.accessKeyID = string(accessKeyID) s.secretAccessKey = string(secretAccessKey) // do this only once here setGlobalConfigPath(root) c.Assert(saveConfig(conf), IsNil) cloudServer := cloudServerConfig{ Address: ":" + strconv.Itoa(getFreePort()), Path: fsroot, MinFreeDisk: 0, AccessKeyID: s.accessKeyID, SecretAccessKey: s.secretAccessKey, Region: "us-east-1", } httpHandler := serverHandler(cloudServer) testAPIFSCacheServer = httptest.NewServer(httpHandler) }
func TestRootTempDir(t *testing.T) { d, err := ioutil.TempDir("", "testroottempdir") if err != nil { t.Fatal(err) } defer os.RemoveAll(d) old := os.Getenv("TMPDIR") cleanup, err := RootTempDir(d) if err != nil { t.Fatal(err) } testDir, err := ioutil.TempDir("", "testroottempsubdir") if err != nil { t.Fatal(err) } _, err = os.Stat(testDir) if err != nil { t.Fatal(err) } cleanup() _, err = os.Stat(testDir) if err == nil || !os.IsNotExist(err) { os.RemoveAll(testDir) t.Errorf("Cleanup did not delete sub temp dir %v", testDir) } if os.Getenv("TMPDIR") != old { t.Error("Failed to restore TMPDIR") } }
func TestUninstall(t *testing.T) { serviceBuilder := runit.FakeServiceBuilder() serviceBuilderDir, err := ioutil.TempDir("", "servicebuilderDir") Assert(t).IsNil(err, "Got an unexpected error creating a temp directory") serviceBuilder.ConfigRoot = serviceBuilderDir 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.OriginalBytes() 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") }
// Test directory with 1 file and 1 non-empty directory func TestSizeFileAndNestedDirectoryNonempty(t *testing.T) { var dir, dirNested string var err error if dir, err = ioutil.TempDir(os.TempDir(), "TestSizeFileAndNestedDirectoryNonempty"); err != nil { t.Fatalf("failed to create directory: %s", err) } if dirNested, err = ioutil.TempDir(dir, "nested"); err != nil { t.Fatalf("failed to create nested directory: %s", err) } var file *os.File if file, err = ioutil.TempFile(dir, "file"); err != nil { t.Fatalf("failed to create file: %s", err) } data := []byte{100, 111, 99, 107, 101, 114} file.Write(data) var nestedFile *os.File if nestedFile, err = ioutil.TempFile(dirNested, "file"); err != nil { t.Fatalf("failed to create file in nested directory: %s", err) } nestedData := []byte{100, 111, 99, 107, 101, 114} nestedFile.Write(nestedData) var size int64 if size, _ = Size(dir); size != 12 { t.Fatalf("directory with 6-byte file and nested directory with 6-byte file has size: %d", size) } }
func TestManifestType(t *testing.T) { pth, _ := ioutil.TempDir("", "_GOTEST_MANIFEST_TYPE") defer os.RemoveAll(pth) m, err := bagins.NewManifest(pth, "sha512", bagins.PayloadManifest) if err != nil { t.Error("Manifest could not be created!", err) } if m.Type() != bagins.PayloadManifest { t.Errorf("Type() expected '%s', got '%s'", bagins.PayloadManifest, m.Type()) } pth, _ = ioutil.TempDir("", "_GOTEST_MANIFEST_TYPE/tagmanifest-sha512.txt") defer os.RemoveAll(pth) m, err = bagins.NewManifest(pth, "sha512", bagins.TagManifest) if err != nil { t.Error("Manifest could not be created!", err) } if m.Type() != bagins.TagManifest { t.Errorf("Type() expected '%s', got '%s'", bagins.TagManifest, m.Type()) } }
func TestScanPath(t *testing.T) { dir1, _ := ioutil.TempDir("", "yegonesh_dir1") dir2, _ := ioutil.TempDir("", "yegonesh_dir2") defer os.RemoveAll(dir1) defer os.RemoveAll(dir2) files := []struct { name string dir string }{ {"vim", dir1}, {"emacs", dir2}, {"nano", dir2}, } for _, f := range files { ioutil.WriteFile(f.dir+"/"+f.name, nil, 0744) } out := scanPath(dir1 + ":" + dir2) expected := []string{"emacs", "nano", "vim"} var result []string for c := range out { result = append(result, c) } if !reflect.DeepEqual(expected, result) { t.Errorf("Expected executables to eq %v, got %v", expected, result) } }
func TestCollectDirectoryRecursive(t *testing.T) { file1, _ := ioutil.TempFile("", "mvshaker") defer os.Remove(file1.Name()) file2, _ := ioutil.TempFile("", "mvshaker") defer os.Remove(file2.Name()) dir, _ := ioutil.TempDir("", "mvshaker") defer os.Remove(dir) file3, _ := ioutil.TempFile(dir, "mvshaker") defer os.Remove(file3.Name()) dir2, _ := ioutil.TempDir(dir, "mvshaker") defer os.Remove(dir2) file4, _ := ioutil.TempFile(dir2, "mvshaker") defer os.Remove(file4.Name()) filesToCollect := []string{file1.Name(), file2.Name(), dir} paths := collect(filesToCollect, []string{}, true) sort.Sort(ByPath(paths)) expected := []shakableFile{ shakableFile{filepath: file1.Name(), isShaked: false}, shakableFile{filepath: file2.Name(), isShaked: false}, shakableFile{filepath: file3.Name(), isShaked: false}, shakableFile{filepath: file4.Name(), isShaked: false}} sort.Sort(ByPath(expected)) assert.Equal(t, paths, expected) }
func TestWriteDHParam(t *testing.T) { // Ensure sslPath/dhparam.pem exists with the contents of routerConfig.SSLConfig.DHParam and is 0644 sslPath, err := ioutil.TempDir("", "test") if err != nil { t.Error(err) } defer os.RemoveAll(sslPath) dhParamPath := filepath.Join(sslPath, "dhparam.pem") expectedDHParam := "bizbar" routerConfig := model.RouterConfig{ SSLConfig: &model.SSLConfig{ DHParam: expectedDHParam, }, } err = WriteDHParam(&routerConfig, sslPath) if err != nil { t.Error(err) } actualDHParam, err := ioutil.ReadFile(dhParamPath) if err != nil { t.Error(err) } if !reflect.DeepEqual(expectedDHParam, string(actualDHParam)) { t.Errorf("Expected dhparam.pem contents, %s, does not match actual contents, %s.", expectedDHParam, string(actualDHParam)) } expectedPerm := "-rw-r--r--" // 0644 info, _ := os.Stat(dhParamPath) actualPerm := info.Mode().String() if !reflect.DeepEqual(expectedPerm, actualPerm) { t.Errorf("Expected permission on dhparam.pem, %s, does not match actual, %s.", expectedPerm, actualPerm) } // Ensure dhparam.pem is erased when routerConfig.SSLConfig.DHParam is empty sslPath, err = ioutil.TempDir("", "test-empty") if err != nil { t.Error(err) } defer os.RemoveAll(sslPath) dhParamPath = filepath.Join(sslPath, "dhparam.pem") routerConfig = model.RouterConfig{ SSLConfig: &model.SSLConfig{ DHParam: "", }, } err = WriteDHParam(&routerConfig, sslPath) if err != nil { t.Error(err) } if _, err := os.Stat(dhParamPath); err == nil { t.Errorf("Expected dhparam.pem to be erased when DHParam was an empty string, but the file was found.") } }
// newLightningNode creates a new test lightning node instance from the passed // rpc config and slice of extra arguments. func newLightningNode(rpcConfig *btcrpcclient.ConnConfig, lndArgs []string) (*lightningNode, error) { var err error cfg := &config{ RPCHost: "127.0.0.1", RPCUser: rpcConfig.User, RPCPass: rpcConfig.Pass, } nodeNum := numActiveNodes cfg.DataDir, err = ioutil.TempDir("", "lndtest-data") if err != nil { return nil, err } cfg.LogDir, err = ioutil.TempDir("", "lndtest-log") if err != nil { return nil, err } cfg.PeerPort, cfg.RPCPort = generateListeningPorts() numActiveNodes++ return &lightningNode{ cfg: cfg, p2pAddr: net.JoinHostPort("127.0.0.1", strconv.Itoa(cfg.PeerPort)), rpcAddr: net.JoinHostPort("127.0.0.1", strconv.Itoa(cfg.RPCPort)), rpcCert: rpcConfig.Certificates, nodeId: nodeNum, extraArgs: lndArgs, }, nil }
func TestMountRequest(t *testing.T) { StartTest(t) defer FinishTest(t) TestRequiresRoot(t) // Start the initd process. _, socket, _, pid := StartInitd(t) content := uuid.Variant4().String() tempDir, err := ioutil.TempDir("/var", "container"+uuid.Variant4().String()) TestExpectSuccess(t, err) AddTestFinalizer(func() { os.RemoveAll(tempDir) }) err = os.Chmod(tempDir, os.FileMode(0755)) TestExpectSuccess(t, err) TestExpectSuccess(t, ioutil.WriteFile(filepath.Join(tempDir, "foo"), []byte(content), os.FileMode(0644))) otherTempDir, err := ioutil.TempDir("/var", "container"+uuid.Variant4().String()) TestExpectSuccess(t, err) AddTestFinalizer(func() { os.RemoveAll(otherTempDir) }) request := [][]string{ []string{"MOUNT", tempDir, otherTempDir}, []string{"", fmt.Sprintf("%d", syscall.MS_BIND), ""}, } reply, err := MakeRequest(socket, request, 10*time.Second) TestExpectSuccess(t, err) TestEqual(t, reply, "REQUEST OK\n") // Next check to see that the init daemon is mounted the path correctly. contents, err := ioutil.ReadFile(filepath.Join(fmt.Sprintf("/proc/%d/root", pid), otherTempDir, "foo")) TestExpectSuccess(t, err) TestEqual(t, string(contents), content) }
// https://gist.github.com/kyanny/c231f48e5d08b98ff2c3 func TestList_Symlink(t *testing.T) { RegisterTestingT(t) root, err := ioutil.TempDir("", "") Expect(err).To(BeNil()) symDir, err := ioutil.TempDir("", "") Expect(err).To(BeNil()) _localRepositoryRoots = []string{root} err = os.MkdirAll(filepath.Join(root, "github.com", "atom", "atom", ".git"), 0777) Expect(err).To(BeNil()) err = os.MkdirAll(filepath.Join(root, "github.com", "zabbix", "zabbix", ".git"), 0777) Expect(err).To(BeNil()) err = os.Symlink(symDir, filepath.Join(root, "github.com", "ghq")) Expect(err).To(BeNil()) paths := []string{} walkLocalRepositories(func(repo *LocalRepository) { paths = append(paths, repo.RelPath) }) Expect(paths).To(HaveLen(2)) }
func (s *TestSuite) TestDiffDirs(c *C) { /// filesystem root1, err := ioutil.TempDir(os.TempDir(), "cmd-") c.Assert(err, IsNil) defer os.RemoveAll(root1) root2, err := ioutil.TempDir(os.TempDir(), "cmd-") c.Assert(err, IsNil) defer os.RemoveAll(root2) var perr *probe.Error for i := 0; i < 10; i++ { objectPath := filepath.Join(root1, "object"+strconv.Itoa(i)) data := "hello" dataLen := len(data) perr = putTarget(objectPath, int64(dataLen), bytes.NewReader([]byte(data))) c.Assert(perr, IsNil) } for i := 0; i < 10; i++ { objectPath := filepath.Join(root2, "object"+strconv.Itoa(i)) data := "hello" dataLen := len(data) perr = putTarget(objectPath, int64(dataLen), bytes.NewReader([]byte(data))) c.Assert(perr, IsNil) } for diff := range doDiffMain(root1, root2, false) { c.Assert(diff.Error, IsNil) } }
func FakeHoistLaunchableForDir(dirName string) (*Launchable, *runit.ServiceBuilder) { tempDir, _ := ioutil.TempDir("", "fakeenv") launchableInstallDir := util.From(runtime.Caller(0)).ExpandPath(dirName) launchable := &Launchable{ Location: "testLaunchable.tar.gz", Id: "testPod__testLaunchable", RunAs: "testPod", PodEnvDir: tempDir, Fetcher: uri.DefaultFetcher, RootDir: launchableInstallDir, P2Exec: util.From(runtime.Caller(0)).ExpandPath("fake_p2-exec"), } curUser, err := user.Current() if err == nil { launchable.RunAs = curUser.Username } sbTemp, _ := ioutil.TempDir("", "fakesvdir") sb := &runit.ServiceBuilder{ RunitRoot: sbTemp, } executables, _ := launchable.Executables(sb) for _, exe := range executables { os.MkdirAll(exe.Service.Path, 0644) } return launchable, sb }
// setup creates a source and destination directory and fills the source with some // files/folders func setup() (src, dst, file string, paths []string, err error) { file = "file.txt" paths = []string{ "", "deep", "deep/deep", "deep/deep/deep", } // if src, err = ioutil.TempDir("", "src"); err != nil { return src, dst, file, paths, err } // if dst, err = ioutil.TempDir("", "dst"); err != nil { return src, dst, file, paths, err } // for _, path := range paths { if err := os.MkdirAll(filepath.Join(src, path), 0755); err != nil { return src, dst, file, paths, err } if err := ioutil.WriteFile(filepath.Join(src, path, file), []byte("contents"), 0644); err != nil { return src, dst, file, paths, err } } return }
func (s *CmdTestSuite) TestCpTypeB(c *C) { /// filesystem source, err := ioutil.TempDir(os.TempDir(), "cmd-") c.Assert(err, IsNil) defer os.RemoveAll(source) sourcePath := filepath.Join(source, "object1") data := "hello" dataLen := len(data) err = putTarget(sourcePath, int64(dataLen), bytes.NewReader([]byte(data))) c.Assert(err, IsNil) target, err := ioutil.TempDir(os.TempDir(), "cmd-") c.Assert(err, IsNil) defer os.RemoveAll(target) cps, err := newSession() c.Assert(err, IsNil) cps.URLs = append(cps.URLs, sourcePath) cps.URLs = append(cps.URLs, target) for err := range doCopyCmdSession(barCp, cps) { c.Assert(err, IsNil) } cps, err = newSession() c.Assert(err, IsNil) targetURL := server.URL + "/bucket" cps.URLs = append(cps.URLs, sourcePath) cps.URLs = append(cps.URLs, targetURL) for err := range doCopyCmdSession(barCp, cps) { c.Assert(err, IsNil) } }
func TestFileSS_BadPerm(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("skipping file permission test on windows") } // Create a temp dir dir1, err := ioutil.TempDir("", "raft") if err != nil { t.Fatalf("err: %s", err) } defer os.RemoveAll(dir1) // Create a sub dir and remove all permissions dir2, err := ioutil.TempDir(dir1, "badperm") if err != nil { t.Fatalf("err: %s", err) } if err := os.Chmod(dir2, 000); err != nil { t.Fatalf("err: %s", err) } defer os.Chmod(dir2, 777) // Set perms back for delete // Should fail if _, err := NewFileSnapshotStore(dir2, 3, nil); err == nil { t.Fatalf("should fail to use dir with bad perms") } }
func TestExpandInjectedFiles(t *testing.T) { tmp, err := ioutil.TempDir("", "s2i-test-") tmpNested, err := ioutil.TempDir(tmp, "nested") if err != nil { t.Errorf("Unable to create temp directory: %v", err) } defer os.RemoveAll(tmp) list := api.VolumeList{{Source: tmp, Destination: "/foo"}} f1, _ := ioutil.TempFile(tmp, "foo") f2, _ := ioutil.TempFile(tmpNested, "bar") files, err := ExpandInjectedFiles(list) if err != nil { t.Errorf("Unexpected error: %v", err) } expected := []string{"/foo/" + filepath.Base(f1.Name()), filepath.Join("/foo", filepath.Base(tmpNested), filepath.Base(f2.Name()))} for _, exp := range expected { found := false for _, f := range files { if f == exp { found = true } } if !found { t.Errorf("Expected %q in resulting file list, got %+v", exp, files) } } }
func prepare() (dir1, dir2 string, ps *store.Store, clog *commit.Logger, rerr error) { var err error dir1, err = ioutil.TempDir("", "storetest_") if err != nil { return "", "", nil, nil, err } ps = new(store.Store) ps.Init(dir1) dir2, err = ioutil.TempDir("", "storemuts_") if err != nil { return dir1, "", nil, nil, err } clog = commit.NewLogger(dir2, "mutations", 50<<20) clog.Init() posting.Init(clog) worker.Init(ps) uid.Init(ps) loader.Init(ps, ps) f, err := os.Open("testdata.nq") if err != nil { return dir1, dir2, nil, clog, err } defer f.Close() _, err = loader.HandleRdfReader(f, 0, 1) if err != nil { return dir1, dir2, nil, clog, err } return dir1, dir2, ps, clog, nil }
// Clear closes the existing WAL and moves away the WAL and snapshot. func (e *EncryptedRaftLogger) Clear(ctx context.Context) error { e.encoderMu.Lock() defer e.encoderMu.Unlock() if e.wal != nil { if err := e.wal.Close(); err != nil { log.G(ctx).WithError(err).Error("error closing raft WAL") } } e.snapshotter = nil newWALDir, err := ioutil.TempDir(e.StateDir, "wal.") if err != nil { return err } os.RemoveAll(newWALDir) if err = os.Rename(e.walDir(), newWALDir); err != nil { return err } newSnapDir, err := ioutil.TempDir(e.StateDir, "snap.") if err != nil { return err } os.RemoveAll(newSnapDir) if err := os.Rename(e.snapDir(), newSnapDir); err != nil { return err } return nil }
func checkNoChanges(fileNum int, hardlinks bool) error { srcDir, err := ioutil.TempDir("", "docker-test-srcDir") if err != nil { return err } defer os.RemoveAll(srcDir) destDir, err := ioutil.TempDir("", "docker-test-destDir") if err != nil { return err } defer os.RemoveAll(destDir) _, err = prepareUntarSourceDirectory(fileNum, srcDir, hardlinks) if err != nil { return err } err = TarUntar(srcDir, destDir) if err != nil { return err } changes, err := ChangesDirs(destDir, srcDir) if err != nil { return err } if len(changes) > 0 { return fmt.Errorf("with %d files and %v hardlinks: expected 0 changes, got %d", fileNum, hardlinks, len(changes)) } return nil }
func TestConsulNode(t *testing.T) { dir, err := ioutil.TempDir("", "mailbox") if err != nil { panic(err) } defer os.RemoveAll(dir) cn1, err := NewConsulClusterNode( &ConsulNodeConfig{ AdvertiseAddr: "127.0.0.1", ListenPort: 8899, DataPath: dir}) if err != nil { panic(err) } defer cn1.Close() go cn1.Accept() dir2, err := ioutil.TempDir("", "mailbox") if err != nil { panic(err) } defer os.RemoveAll(dir2) cn2, err := NewConsulClusterNode( &ConsulNodeConfig{ AdvertiseAddr: "127.0.0.1", ListenPort: 9900, DataPath: dir2}) if err != nil { panic(err) } defer cn2.Close() go cn2.Accept() cn1.Declare("a") // propagation delay time.Sleep(1000 * time.Millisecond) msg := vega.Msg([]byte("hello")) // debugf("pushing...\n") err = cn2.Push("a", msg) require.NoError(t, err) // debugf("polling...\n") got, err := cn1.Poll("a") if err != nil { panic(err) } assert.True(t, got.Message.Equal(msg), "didn't get the message") }
// useDirperm checks dirperm1 mount option can be used with the current // version of aufs. func useDirperm() bool { enableDirpermLock.Do(func() { base, err := ioutil.TempDir("", "docker-aufs-base") if err != nil { logrus.Errorf("error checking dirperm1: %v", err) return } defer os.RemoveAll(base) union, err := ioutil.TempDir("", "docker-aufs-union") if err != nil { logrus.Errorf("error checking dirperm1: %v", err) return } defer os.RemoveAll(union) opts := fmt.Sprintf("br:%s,dirperm1,xino=/dev/shm/aufs.xino", base) if err := mount("none", union, "aufs", 0, opts); err != nil { return } enableDirperm = true if err := Unmount(union); err != nil { logrus.Errorf("error checking dirperm1: failed to unmount %v", err) } }) return enableDirperm }
// NewGitUtil creates a git utility. func NewGitUtil() (*GitUtil, error) { workDir, err := ioutil.TempDir("", "") if err != nil { return nil, err } // setup git env dir, err := ioutil.TempDir("", "") if err != nil { return nil, err } // since some system return the symbolic path from git, we have to convert it back to // the real absolute path. workDir, err = filepath.EvalSymlinks(dir) if err != nil { return nil, err } gitDir := filepath.Join(workDir, ".git") g := &GitUtil{ gitCmdPrefix: fmt.Sprintf("git --git-dir %s --work-tree %s", gitDir, workDir), workDir: workDir, } // init git command ExecStrCmds(g.gitInitCmds()) return g, nil }