ulimit_test.go 2.21 KB
Newer Older
1 2
// +build !windows

3 4 5 6 7 8 9 10 11 12 13 14
package util

import (
	"fmt"
	"os"
	"strings"
	"syscall"
	"testing"
)

func TestManageFdLimit(t *testing.T) {
	t.Log("Testing file descriptor count")
15
	if _, _, err := ManageFdLimit(); err != nil {
16 17 18
		t.Errorf("Cannot manage file descriptors")
	}

Steven Allen's avatar
Steven Allen committed
19
	if maxFds != uint64(8192) {
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
		t.Errorf("Maximum file descriptors default value changed")
	}
}

func TestManageInvalidNFds(t *testing.T) {
	t.Logf("Testing file descriptor invalidity")
	var err error
	if err = os.Unsetenv("IPFS_FD_MAX"); err != nil {
		t.Fatal("Cannot unset the IPFS_FD_MAX env variable")
	}

	rlimit := syscall.Rlimit{}
	if err = syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rlimit); err != nil {
		t.Fatal("Cannot get the file descriptor count")
	}

	value := rlimit.Max + rlimit.Cur
	if err = os.Setenv("IPFS_FD_MAX", fmt.Sprintf("%d", value)); err != nil {
		t.Fatal("Cannot set the IPFS_FD_MAX env variable")
	}

Steven Allen's avatar
Steven Allen committed
41 42 43 44
	t.Logf("setting ulimit to %d, max %d, cur %d", value, rlimit.Max, rlimit.Cur)

	if changed, new, err := ManageFdLimit(); err == nil {
		t.Errorf("ManageFdLimit should return an error: changed %t, new: %d", changed, new)
45 46
	} else if err != nil {
		flag := strings.Contains(err.Error(),
Steven Allen's avatar
Steven Allen committed
47
			"failed to raise ulimit to IPFS_FD_MAX")
48
		if !flag {
Steven Allen's avatar
Steven Allen committed
49
			t.Error("ManageFdLimit returned unexpected error", err)
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
		}
	}

	// unset all previous operations
	if err = os.Unsetenv("IPFS_FD_MAX"); err != nil {
		t.Fatal("Cannot unset the IPFS_FD_MAX env variable")
	}
}

func TestManageFdLimitWithEnvSet(t *testing.T) {
	t.Logf("Testing file descriptor manager with IPFS_FD_MAX set")
	var err error
	if err = os.Unsetenv("IPFS_FD_MAX"); err != nil {
		t.Fatal("Cannot unset the IPFS_FD_MAX env variable")
	}

	rlimit := syscall.Rlimit{}
	if err = syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rlimit); err != nil {
		t.Fatal("Cannot get the file descriptor count")
	}

	value := rlimit.Max - rlimit.Cur + 1
	if err = os.Setenv("IPFS_FD_MAX", fmt.Sprintf("%d", value)); err != nil {
		t.Fatal("Cannot set the IPFS_FD_MAX env variable")
	}

76
	if _, _, err = ManageFdLimit(); err != nil {
77 78 79 80 81 82 83 84
		t.Errorf("Cannot manage file descriptor count")
	}

	// unset all previous operations
	if err = os.Unsetenv("IPFS_FD_MAX"); err != nil {
		t.Fatal("Cannot unset the IPFS_FD_MAX env variable")
	}
}