ulimit_unix.go 1.09 KB
Newer Older
Vasily Kolobkov's avatar
Vasily Kolobkov committed
1
// +build darwin freebsd linux netbsd openbsd
Jeromy's avatar
Jeromy committed
2 3 4 5 6 7 8 9 10 11

package main

import (
	"fmt"
	"os"
	"strconv"
	"syscall"
)

12
var ipfsFileDescNum = uint64(1024)
Jeromy's avatar
Jeromy committed
13 14 15 16 17

func init() {
	if val := os.Getenv("IPFS_FD_MAX"); val != "" {
		n, err := strconv.Atoi(val)
		if err != nil {
18
			log.Errorf("bad value for IPFS_FD_MAX: %s", err)
Jeromy's avatar
Jeromy committed
19 20 21 22 23 24 25 26 27 28 29 30 31 32
		} else {
			ipfsFileDescNum = uint64(n)
		}
	}
	fileDescriptorCheck = checkAndSetUlimit
}

func checkAndSetUlimit() error {
	var rLimit syscall.Rlimit
	err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rLimit)
	if err != nil {
		return fmt.Errorf("error getting rlimit: %s", err)
	}

33
	var setting bool
Jeromy's avatar
Jeromy committed
34
	if rLimit.Cur < ipfsFileDescNum {
Jeromy's avatar
Jeromy committed
35
		if rLimit.Max < ipfsFileDescNum {
36
			log.Error("adjusting max")
Jeromy's avatar
Jeromy committed
37 38
			rLimit.Max = ipfsFileDescNum
		}
39
		fmt.Printf("Adjusting current ulimit to %d...\n", ipfsFileDescNum)
Jeromy's avatar
Jeromy committed
40
		rLimit.Cur = ipfsFileDescNum
41
		setting = true
Jeromy's avatar
Jeromy committed
42 43 44 45 46 47 48
	}

	err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rLimit)
	if err != nil {
		return fmt.Errorf("error setting ulimit: %s", err)
	}

49 50 51 52
	if setting {
		fmt.Printf("Successfully raised file descriptor limit to %d.\n", ipfsFileDescNum)
	}

Jeromy's avatar
Jeromy committed
53 54
	return nil
}