fdlimit_darwin.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright 2016 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package fdlimit
  17. import "syscall"
  18. // hardlimit is the number of file descriptors allowed at max by the kernel.
  19. const hardlimit = 10240
  20. // Raise tries to maximize the file descriptor allowance of this process
  21. // to the maximum hard-limit allowed by the OS.
  22. // Returns the size it was set to (may differ from the desired 'max')
  23. func Raise(max uint64) (uint64, error) {
  24. // Get the current limit
  25. var limit syscall.Rlimit
  26. if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil {
  27. return 0, err
  28. }
  29. // Try to update the limit to the max allowance
  30. limit.Cur = limit.Max
  31. if limit.Cur > max {
  32. limit.Cur = max
  33. }
  34. if err := syscall.Setrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil {
  35. return 0, err
  36. }
  37. // MacOS can silently apply further caps, so retrieve the actually set limit
  38. if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil {
  39. return 0, err
  40. }
  41. return limit.Cur, nil
  42. }
  43. // Current retrieves the number of file descriptors allowed to be opened by this
  44. // process.
  45. func Current() (int, error) {
  46. var limit syscall.Rlimit
  47. if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil {
  48. return 0, err
  49. }
  50. return int(limit.Cur), nil
  51. }
  52. // Maximum retrieves the maximum number of file descriptors this process is
  53. // allowed to request for itself.
  54. func Maximum() (int, error) {
  55. // Retrieve the maximum allowed by dynamic OS limits
  56. var limit syscall.Rlimit
  57. if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil {
  58. return 0, err
  59. }
  60. // Cap it to OPEN_MAX (10240) because macos is a special snowflake
  61. if limit.Max > hardlimit {
  62. limit.Max = hardlimit
  63. }
  64. return int(limit.Max), nil
  65. }