github.com/hpcng/singularity@v3.1.1+incompatible/pkg/util/rlimit/rlimit_linux.go (about)

     1  // Copyright (c) 2018, Sylabs Inc. All rights reserved.
     2  // This software is licensed under a 3-clause BSD license. Please consult the
     3  // LICENSE.md file distributed with the sources of this project regarding your
     4  // rights to use or distribute this software.
     5  
     6  package rlimit
     7  
     8  import (
     9  	"fmt"
    10  	"syscall"
    11  )
    12  
    13  var resource = map[string]int{
    14  	"RLIMIT_CPU":        0,
    15  	"RLIMIT_FSIZE":      1,
    16  	"RLIMIT_DATA":       2,
    17  	"RLIMIT_STACK":      3,
    18  	"RLIMIT_CORE":       4,
    19  	"RLIMIT_RSS":        5,
    20  	"RLIMIT_NPROC":      6,
    21  	"RLIMIT_NOFILE":     7,
    22  	"RLIMIT_MEMLOCK":    8,
    23  	"RLIMIT_AS":         9,
    24  	"RLIMIT_LOCKS":      10,
    25  	"RLIMIT_SIGPENDING": 11,
    26  	"RLIMIT_MSGQUEUE":   12,
    27  	"RLIMIT_NICE":       13,
    28  	"RLIMIT_RTPRIO":     14,
    29  	"RLIMIT_RTTIME":     15,
    30  }
    31  
    32  // Set sets soft and hard resource limit
    33  func Set(res string, cur uint64, max uint64) error {
    34  	var rlim syscall.Rlimit
    35  
    36  	resVal, ok := resource[res]
    37  	if !ok {
    38  		return fmt.Errorf("%s is not a valid resource type", res)
    39  	}
    40  
    41  	rlim.Cur = cur
    42  	rlim.Max = max
    43  
    44  	if err := syscall.Setrlimit(resVal, &rlim); err != nil {
    45  		return fmt.Errorf("failed to set resource limit %s: %s", res, err)
    46  	}
    47  
    48  	return nil
    49  }
    50  
    51  // Get retrieves soft and hard resource limit
    52  func Get(res string) (cur uint64, max uint64, err error) {
    53  	var rlim syscall.Rlimit
    54  
    55  	resVal, ok := resource[res]
    56  	if !ok {
    57  		err = fmt.Errorf("%s is not a valid resource type", res)
    58  		return
    59  	}
    60  
    61  	if err = syscall.Getrlimit(resVal, &rlim); err != nil {
    62  		err = fmt.Errorf("failed to get resource limit %s: %s", res, err)
    63  		return
    64  	}
    65  
    66  	cur = rlim.Cur
    67  	max = rlim.Max
    68  
    69  	return
    70  }