Skip to content

Instantly share code, notes, and snippets.

@kaorimatz
Created April 12, 2015 08:12
Show Gist options
  • Save kaorimatz/8190d16d2a0df91ff5cd to your computer and use it in GitHub Desktop.
Save kaorimatz/8190d16d2a0df91ff5cd to your computer and use it in GitHub Desktop.
package main
import (
"bufio"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"os"
"strconv"
"strings"
)
type ResourceLimit struct {
Name string
SoftLimit ResourceLimitValue
HardLimit ResourceLimitValue
Unit string
}
func ReadResourceLimits(pid int) ([]ResourceLimit, error) {
file, err := os.Open(fmt.Sprintf("/proc/%d/limits", pid))
if err != nil {
return nil, err
}
reader := bufio.NewReader(file)
var limits []ResourceLimit
var nameIndex, softLimitIndex, hardLimitIndex, unitIndex int
for i := 0; ; i++ {
line, err := reader.ReadString('\n')
if len(line) == 0 && err == io.EOF {
break
}
if err != nil {
return nil, err
}
if i == 0 {
nameIndex = strings.Index(line, "Limit")
softLimitIndex = strings.Index(line, "Soft Limit")
hardLimitIndex = strings.Index(line, "Hard Limit")
unitIndex = strings.Index(line, "Units")
} else {
name := strings.TrimSpace(line[nameIndex:softLimitIndex])
unit := strings.TrimSpace(line[unitIndex:])
softLimit, err := ParseResourceLimitValue(strings.TrimSpace(line[softLimitIndex:hardLimitIndex]))
if err != nil {
return nil, err
}
hardLimit, err := ParseResourceLimitValue(strings.TrimSpace(line[hardLimitIndex:unitIndex]))
if err != nil {
return nil, err
}
limit := ResourceLimit{
Name: name,
SoftLimit: softLimit,
HardLimit: hardLimit,
Unit: unit,
}
limits = append(limits, limit)
}
}
return limits, nil
}
type ResourceLimitValue uint64
func ParseResourceLimitValue(s string) (ResourceLimitValue, error) {
if s == "unlimited" {
return ResourceLimitUnlimited, nil
}
v, err := strconv.ParseUint(s, 0, 64)
if err != nil {
return 0, nil
}
return ResourceLimitValue(v), nil
}
func (v ResourceLimitValue) String() string {
if v == ResourceLimitUnlimited {
return "unlimited"
}
return fmt.Sprint(uint64(v))
}
func (v ResourceLimitValue) MarshalJSON() ([]byte, error) {
if v == ResourceLimitUnlimited {
return json.Marshal(nil)
}
return json.Marshal(uint64(v))
}
const (
ResourceLimitUnlimited = ResourceLimitValue(^uint64(0))
)
func main() {
pid := flag.Int("pid", 1, "Target PID")
flag.Parse()
limits, err := ReadResourceLimits(*pid)
if err != nil {
log.Fatal(err)
}
json, err := json.MarshalIndent(limits, "", " ")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(json))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment