github.com/lbryio/lbcd@v0.22.119/limits/limits_unix.go (about)

     1  // Copyright (c) 2013-2014 The btcsuite developers
     2  // Use of this source code is governed by an ISC
     3  // license that can be found in the LICENSE file.
     4  
     5  //go:build !windows && !plan9
     6  // +build !windows,!plan9
     7  
     8  package limits
     9  
    10  import (
    11  	"fmt"
    12  	"syscall"
    13  )
    14  
    15  const (
    16  	fileLimitWant = 2048 * 12
    17  	fileLimitMin  = 2048 * 8
    18  )
    19  
    20  // SetLimits raises some process limits to values which allow btcd and
    21  // associated utilities to run.
    22  func SetLimits() error {
    23  	var rLimit syscall.Rlimit
    24  
    25  	err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rLimit)
    26  	if err != nil {
    27  		return err
    28  	}
    29  	if rLimit.Cur > fileLimitWant {
    30  		return nil
    31  	}
    32  	if rLimit.Max < fileLimitMin {
    33  		err = fmt.Errorf("need at least %v file descriptors",
    34  			fileLimitMin)
    35  		return err
    36  	}
    37  	if rLimit.Max < fileLimitWant {
    38  		rLimit.Cur = rLimit.Max
    39  	} else {
    40  		rLimit.Cur = fileLimitWant
    41  	}
    42  	err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rLimit)
    43  	if err != nil {
    44  		// try min value
    45  		rLimit.Cur = fileLimitMin
    46  		err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rLimit)
    47  		if err != nil {
    48  			return err
    49  		}
    50  	}
    51  
    52  	return nil
    53  }