├── procfs ├── NOTICE ├── AUTHORS.md ├── fs.go ├── stat.go ├── proc.go ├── proc_stat.go └── LICENSE ├── README.md ├── cmd ├── demo-cpu │ └── main.go └── demo-heap │ └── main.go ├── cpu └── cpu.go └── heap └── heap.go /procfs/NOTICE: -------------------------------------------------------------------------------- 1 | procfs provides functions to retrieve system, kernel and process 2 | metrics from the pseudo-filesystem proc. 3 | 4 | Copyright 2014-2015 The Prometheus Authors 5 | 6 | This product includes software developed at 7 | SoundCloud Ltd. (http://soundcloud.com/). 8 | -------------------------------------------------------------------------------- /procfs/AUTHORS.md: -------------------------------------------------------------------------------- 1 | The Prometheus project was started by Matt T. Proud (emeritus) and 2 | Julius Volz in 2012. 3 | 4 | Maintainers of this repository: 5 | 6 | * Tobias Schmidt 7 | 8 | The following individuals have contributed code to this repository 9 | (listed in alphabetical order): 10 | 11 | * Ji-Hoon, Seol 12 | * Tobias Schmidt 13 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Go Report Card](https://goreportcard.com/badge/github.com/Dieterbe/profiletrigger)](https://goreportcard.com/report/github.com/Dieterbe/profiletrigger) 2 | [![GoDoc](https://godoc.org/github.com/Dieterbe/profiletrigger?status.svg)](https://godoc.org/github.com/Dieterbe/profiletrigger) 3 | 4 | automatically trigger a profile in your golang (go) application when a condition is matched. 5 | 6 | # currently implemented: 7 | 8 | * when process is using certain number of bytes of RAM, save a heap (memory) profile 9 | * when process cpu usage reaches a certain percentage, save a cpu profile. 10 | 11 | # demo 12 | 13 | see the included cpudemo and heapdemo programs, which gradually add more and cpu and heap utilisation, to show the profiletrigger kicking in. 14 | -------------------------------------------------------------------------------- /procfs/fs.go: -------------------------------------------------------------------------------- 1 | package procfs 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "path" 7 | ) 8 | 9 | // FS represents the pseudo-filesystem proc, which provides an interface to 10 | // kernel data structures. 11 | type FS string 12 | 13 | // DefaultMountPoint is the common mount point of the proc filesystem. 14 | const DefaultMountPoint = "/proc" 15 | 16 | // NewFS returns a new FS mounted under the given mountPoint. It will error 17 | // if the mount point can't be read. 18 | func NewFS(mountPoint string) (FS, error) { 19 | info, err := os.Stat(mountPoint) 20 | if err != nil { 21 | return "", fmt.Errorf("could not read %s: %s", mountPoint, err) 22 | } 23 | if !info.IsDir() { 24 | return "", fmt.Errorf("mount point %s is not a directory", mountPoint) 25 | } 26 | 27 | return FS(mountPoint), nil 28 | } 29 | 30 | func (fs FS) stat(p string) (os.FileInfo, error) { 31 | return os.Stat(path.Join(string(fs), p)) 32 | } 33 | 34 | func (fs FS) open(p string) (*os.File, error) { 35 | return os.Open(path.Join(string(fs), p)) 36 | } 37 | 38 | func (fs FS) readlink(p string) (string, error) { 39 | return os.Readlink(path.Join(string(fs), p)) 40 | } 41 | -------------------------------------------------------------------------------- /cmd/demo-cpu/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "time" 6 | 7 | "github.com/Dieterbe/profiletrigger/cpu" 8 | ) 9 | 10 | var j int 11 | 12 | func cpuUser(dur time.Duration, stopChan chan struct{}) { 13 | tick := time.NewTicker(time.Millisecond) 14 | //fmt.Print("every ms, sleep", dur, " ") 15 | for { 16 | select { 17 | case <-tick.C: 18 | time.Sleep(dur) 19 | case <-stopChan: 20 | return 21 | // if we're not sleeping or stopping, just stay busy and consume cpu 22 | default: 23 | for i := 0; i < 10; i++ { 24 | j = i * 123 25 | } 26 | } 27 | } 28 | } 29 | 30 | func main() { 31 | errors := make(chan error) 32 | trigger, _ := cpu.New(".", 80, 60, time.Duration(1)*time.Second, time.Duration(2)*time.Second, errors) 33 | go trigger.Run() 34 | // gradually build up cpu usage. 35 | for i := 1000; i >= 0; i = i - 50 { 36 | stopChan := make(chan struct{}) 37 | go cpuUser(time.Duration(i)*time.Microsecond, stopChan) 38 | time.Sleep(time.Second) 39 | stopChan <- struct{}{} 40 | } 41 | // end with just 100% cpu usage (1 core) 42 | go cpuUser(0, nil) 43 | 44 | for e := range errors { 45 | log.Fatal("profiletrigger cpu saw error:", e) 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /cmd/demo-heap/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "time" 7 | 8 | "github.com/Dieterbe/profiletrigger/heap" 9 | ) 10 | 11 | type data struct { 12 | d []byte 13 | prev *data 14 | } 15 | 16 | func newData(prev *data, size int) *data { 17 | return &data{ 18 | d: make([]byte, size), 19 | prev: prev, 20 | } 21 | } 22 | 23 | // HungryAllocator allocates 1MB every second 24 | func HungryAllocator() { 25 | var prev *data 26 | for { 27 | n := newData(prev, 1000000) 28 | prev = n 29 | time.Sleep(time.Second) 30 | } 31 | } 32 | 33 | // LightAllocator allocates 100kB every second 34 | func LightAllocator() { 35 | var prev *data 36 | for { 37 | n := newData(prev, 100000) 38 | prev = n 39 | time.Sleep(time.Second) 40 | } 41 | } 42 | 43 | func main() { 44 | fmt.Println("allocating 1100 kB every second. should hit the 10MB threshold within 10 seconds. look for a profile..") 45 | errors := make(chan error) 46 | trigger, _ := heap.New(heap.Config{ 47 | Path: ".", 48 | ThreshHeap: 10000000, 49 | MinTimeDiff: 60 * time.Second, 50 | CheckEvery: time.Second, 51 | }, errors) 52 | 53 | go trigger.Run() 54 | go HungryAllocator() 55 | go LightAllocator() 56 | for e := range errors { 57 | log.Fatal("profiletrigger heap saw error:", e) 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /procfs/stat.go: -------------------------------------------------------------------------------- 1 | package procfs 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "strconv" 7 | "strings" 8 | ) 9 | 10 | // Stat represents kernel/system statistics. 11 | type Stat struct { 12 | // Boot time in seconds since the Epoch. 13 | BootTime int64 14 | } 15 | 16 | // NewStat returns kernel/system statistics read from /proc/stat. 17 | func NewStat() (Stat, error) { 18 | fs, err := NewFS(DefaultMountPoint) 19 | if err != nil { 20 | return Stat{}, err 21 | } 22 | 23 | return fs.NewStat() 24 | } 25 | 26 | // NewStat returns an information about current kernel/system statistics. 27 | func (fs FS) NewStat() (Stat, error) { 28 | f, err := fs.open("stat") 29 | if err != nil { 30 | return Stat{}, err 31 | } 32 | defer f.Close() 33 | 34 | s := bufio.NewScanner(f) 35 | for s.Scan() { 36 | line := s.Text() 37 | if !strings.HasPrefix(line, "btime") { 38 | continue 39 | } 40 | fields := strings.Fields(line) 41 | if len(fields) != 2 { 42 | return Stat{}, fmt.Errorf("couldn't parse %s line %s", f.Name(), line) 43 | } 44 | i, err := strconv.ParseInt(fields[1], 10, 32) 45 | if err != nil { 46 | return Stat{}, fmt.Errorf("couldn't parse %s: %s", fields[1], err) 47 | } 48 | return Stat{BootTime: i}, nil 49 | } 50 | if err := s.Err(); err != nil { 51 | return Stat{}, fmt.Errorf("couldn't parse %s: %s", f.Name(), err) 52 | } 53 | 54 | return Stat{}, fmt.Errorf("couldn't parse %s, missing btime", f.Name()) 55 | } 56 | -------------------------------------------------------------------------------- /cpu/cpu.go: -------------------------------------------------------------------------------- 1 | package cpu 2 | 3 | import ( 4 | "fmt" 5 | "github.com/shirou/gopsutil/process" 6 | "os" 7 | "runtime/pprof" 8 | "time" 9 | ) 10 | 11 | // Cpu will check every checkEvery for cpu percentage used to reach or exceed the threshold and take a cpu profile to the path directory, 12 | // but no more often than every minTimeDiff seconds 13 | // any errors will be sent to the errors channel 14 | // the duration of the cpu profile is controlled via profDur. 15 | type Cpu struct { 16 | path string 17 | threshold int 18 | minTimeDiff int 19 | checkEvery time.Duration 20 | profDur time.Duration 21 | lastUnix int64 22 | Errors chan error 23 | } 24 | 25 | // New creates a new Cpu trigger. use a nil channel if you don't care about any errors 26 | func New(path string, threshold, minTimeDiff int, checkEvery, profDur time.Duration, errors chan error) (*Cpu, error) { 27 | cpu := Cpu{ 28 | path, 29 | threshold, 30 | minTimeDiff, 31 | checkEvery, 32 | profDur, 33 | int64(0), 34 | errors, 35 | } 36 | return &cpu, nil 37 | } 38 | 39 | func (cpu Cpu) logError(err error) { 40 | if cpu.Errors != nil { 41 | cpu.Errors <- err 42 | } 43 | } 44 | 45 | // Run runs the trigger. encountered errors go to the configured channel (if any). 46 | // you probably want to run this in a new goroutine. 47 | func (cpu Cpu) Run() { 48 | tick := time.NewTicker(cpu.checkEvery) 49 | pid := os.Getpid() 50 | p, err := process.NewProcess(int32(pid)) 51 | if err != nil { 52 | cpu.logError(err) 53 | return 54 | } 55 | for ts := range tick.C { 56 | percent, err := p.Percent(0) 57 | if err != nil { 58 | cpu.logError(err) 59 | continue 60 | } 61 | //fmt.Println("percent is now", percent) 62 | unix := ts.Unix() 63 | // we discard the decimals of the percentage. an integer with percent resolution should be good enough. 64 | if int(percent) >= cpu.threshold && unix >= cpu.lastUnix+int64(cpu.minTimeDiff) { 65 | f, err := os.Create(fmt.Sprintf("%s/%d.profile-cpu", cpu.path, unix)) 66 | if err != nil { 67 | cpu.logError(err) 68 | continue 69 | } 70 | err = pprof.StartCPUProfile(f) 71 | if err != nil { 72 | cpu.logError(err) 73 | } 74 | time.Sleep(cpu.profDur) 75 | pprof.StopCPUProfile() 76 | cpu.lastUnix = unix 77 | err = f.Close() 78 | if err != nil { 79 | cpu.logError(err) 80 | } 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /heap/heap.go: -------------------------------------------------------------------------------- 1 | package heap 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "runtime" 7 | "runtime/pprof" 8 | "time" 9 | 10 | "github.com/Dieterbe/profiletrigger/procfs" 11 | ) 12 | 13 | // Heap will check memory at the requested interval and report profiles if thresholds are breached. 14 | // See Config for configuration documentation 15 | // If non-nil, any runtime errors are sent on the errors channel 16 | type Heap struct { 17 | cfg Config 18 | errors chan error 19 | lastTriggered time.Time 20 | proc procfs.Proc 21 | } 22 | 23 | // Config is the config for triggering heap profiles 24 | // It uses HeapAlloc from https://golang.org/pkg/runtime/#MemStats as well as RSS memory usage 25 | type Config struct { 26 | Path string // directory to write profiles to. 27 | ThreshHeap int // number of bytes to compare MemStats.HeapAlloc (bytes of allocated heap objects) to 28 | ThreshRSS int // number of bytes to compare RSS usage to 29 | MinTimeDiff time.Duration // report no more often than this 30 | CheckEvery time.Duration // check both thresholds at this rate 31 | } 32 | 33 | // New creates a new Heap trigger. use a nil channel if you don't care about any errors 34 | func New(cfg Config, errors chan error) (*Heap, error) { 35 | heap := Heap{ 36 | cfg: cfg, 37 | errors: errors, 38 | } 39 | if cfg.ThreshRSS != 0 { 40 | proc, err := procfs.Self() 41 | if err != nil { 42 | return nil, err 43 | } 44 | heap.proc = proc 45 | } 46 | 47 | return &heap, nil 48 | } 49 | 50 | func (heap Heap) logError(err error) { 51 | if heap.errors != nil { 52 | heap.errors <- err 53 | } 54 | } 55 | 56 | // Run runs the trigger. any encountered errors go to the configured errors channel. 57 | // you probably want to run this in a new goroutine. 58 | func (heap Heap) Run() { 59 | cfg := heap.cfg 60 | tick := time.NewTicker(cfg.CheckEvery) 61 | 62 | for ts := range tick.C { 63 | if !heap.shouldProfile(ts) { 64 | continue 65 | } 66 | f, err := os.Create(fmt.Sprintf("%s/%d.profile-heap", cfg.Path, ts.Unix())) 67 | if err != nil { 68 | heap.logError(err) 69 | continue 70 | } 71 | err = pprof.WriteHeapProfile(f) 72 | if err != nil { 73 | heap.logError(err) 74 | } 75 | heap.lastTriggered = ts 76 | err = f.Close() 77 | if err != nil { 78 | heap.logError(err) 79 | } 80 | } 81 | } 82 | 83 | func (heap Heap) shouldProfile(ts time.Time) bool { 84 | cfg := heap.cfg 85 | 86 | if ts.Before(heap.lastTriggered.Add(cfg.MinTimeDiff)) { 87 | return false 88 | } 89 | 90 | // Check RSS. 91 | if cfg.ThreshRSS != 0 { 92 | stat, err := heap.proc.NewStat() 93 | if err != nil { 94 | heap.logError(err) 95 | } else if stat.ResidentMemory() >= cfg.ThreshRSS { 96 | return true 97 | } 98 | } 99 | 100 | // Check HeapAlloc 101 | if cfg.ThreshHeap != 0 { 102 | m := &runtime.MemStats{} 103 | runtime.ReadMemStats(m) 104 | 105 | if m.HeapAlloc >= uint64(cfg.ThreshHeap) { 106 | return true 107 | } 108 | } 109 | 110 | return false 111 | } 112 | -------------------------------------------------------------------------------- /procfs/proc.go: -------------------------------------------------------------------------------- 1 | package procfs 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "os" 7 | "path" 8 | "strconv" 9 | "strings" 10 | ) 11 | 12 | // Proc provides information about a running process. 13 | type Proc struct { 14 | // The process ID. 15 | PID int 16 | 17 | fs FS 18 | } 19 | 20 | // Procs represents a list of Proc structs. 21 | type Procs []Proc 22 | 23 | func (p Procs) Len() int { return len(p) } 24 | func (p Procs) Swap(i, j int) { p[i], p[j] = p[j], p[i] } 25 | func (p Procs) Less(i, j int) bool { return p[i].PID < p[j].PID } 26 | 27 | // Self returns a process for the current process. 28 | func Self() (Proc, error) { 29 | return NewProc(os.Getpid()) 30 | } 31 | 32 | // NewProc returns a process for the given pid under /proc. 33 | func NewProc(pid int) (Proc, error) { 34 | fs, err := NewFS(DefaultMountPoint) 35 | if err != nil { 36 | return Proc{}, err 37 | } 38 | 39 | return fs.NewProc(pid) 40 | } 41 | 42 | // AllProcs returns a list of all currently avaible processes under /proc. 43 | func AllProcs() (Procs, error) { 44 | fs, err := NewFS(DefaultMountPoint) 45 | if err != nil { 46 | return Procs{}, err 47 | } 48 | 49 | return fs.AllProcs() 50 | } 51 | 52 | // NewProc returns a process for the given pid. 53 | func (fs FS) NewProc(pid int) (Proc, error) { 54 | if _, err := fs.stat(strconv.Itoa(pid)); err != nil { 55 | return Proc{}, err 56 | } 57 | 58 | return Proc{PID: pid, fs: fs}, nil 59 | } 60 | 61 | // AllProcs returns a list of all currently avaible processes. 62 | func (fs FS) AllProcs() (Procs, error) { 63 | d, err := fs.open("") 64 | if err != nil { 65 | return Procs{}, err 66 | } 67 | defer d.Close() 68 | 69 | names, err := d.Readdirnames(-1) 70 | if err != nil { 71 | return Procs{}, fmt.Errorf("could not read %s: %s", d.Name(), err) 72 | } 73 | 74 | p := Procs{} 75 | for _, n := range names { 76 | pid, err := strconv.ParseInt(n, 10, 64) 77 | if err != nil { 78 | continue 79 | } 80 | p = append(p, Proc{PID: int(pid), fs: fs}) 81 | } 82 | 83 | return p, nil 84 | } 85 | 86 | // CmdLine returns the command line of a process. 87 | func (p Proc) CmdLine() ([]string, error) { 88 | f, err := p.open("cmdline") 89 | if err != nil { 90 | return nil, err 91 | } 92 | defer f.Close() 93 | 94 | data, err := ioutil.ReadAll(f) 95 | if err != nil { 96 | return nil, err 97 | } 98 | 99 | if len(data) < 1 { 100 | return []string{}, nil 101 | } 102 | 103 | return strings.Split(string(data[:len(data)-1]), string(byte(0))), nil 104 | } 105 | 106 | // Executable returns the absolute path of the executable command of a process. 107 | func (p Proc) Executable() (string, error) { 108 | exe, err := p.readlink("exe") 109 | 110 | if os.IsNotExist(err) { 111 | return "", nil 112 | } 113 | 114 | return exe, err 115 | } 116 | 117 | // FileDescriptors returns the currently open file descriptors of a process. 118 | func (p Proc) FileDescriptors() ([]uintptr, error) { 119 | names, err := p.fileDescriptors() 120 | if err != nil { 121 | return nil, err 122 | } 123 | 124 | fds := make([]uintptr, len(names)) 125 | for i, n := range names { 126 | fd, err := strconv.ParseInt(n, 10, 32) 127 | if err != nil { 128 | return nil, fmt.Errorf("could not parse fd %s: %s", n, err) 129 | } 130 | fds[i] = uintptr(fd) 131 | } 132 | 133 | return fds, nil 134 | } 135 | 136 | // FileDescriptorTargets returns the targets of all file descriptors of a process. 137 | // If a file descriptor is not a symlink to a file (like a socket), that value will be the empty string. 138 | func (p Proc) FileDescriptorTargets() ([]string, error) { 139 | names, err := p.fileDescriptors() 140 | if err != nil { 141 | return nil, err 142 | } 143 | 144 | targets := make([]string, len(names)) 145 | 146 | for i, name := range names { 147 | target, err := p.readlink("fd/" + name) 148 | if err == nil { 149 | targets[i] = target 150 | } 151 | } 152 | 153 | return targets, nil 154 | } 155 | 156 | // FileDescriptorsLen returns the number of currently open file descriptors of 157 | // a process. 158 | func (p Proc) FileDescriptorsLen() (int, error) { 159 | fds, err := p.fileDescriptors() 160 | if err != nil { 161 | return 0, err 162 | } 163 | 164 | return len(fds), nil 165 | } 166 | 167 | func (p Proc) fileDescriptors() ([]string, error) { 168 | d, err := p.open("fd") 169 | if err != nil { 170 | return nil, err 171 | } 172 | defer d.Close() 173 | 174 | names, err := d.Readdirnames(-1) 175 | if err != nil { 176 | return nil, fmt.Errorf("could not read %s: %s", d.Name(), err) 177 | } 178 | 179 | return names, nil 180 | } 181 | 182 | func (p Proc) open(pa string) (*os.File, error) { 183 | return p.fs.open(path.Join(strconv.Itoa(p.PID), pa)) 184 | } 185 | 186 | func (p Proc) readlink(pa string) (string, error) { 187 | return p.fs.readlink(path.Join(strconv.Itoa(p.PID), pa)) 188 | } 189 | -------------------------------------------------------------------------------- /procfs/proc_stat.go: -------------------------------------------------------------------------------- 1 | package procfs 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "io/ioutil" 7 | "os" 8 | ) 9 | 10 | // Originally, this USER_HZ value was dynamically retrieved via a sysconf call which 11 | // required cgo. However, that caused a lot of problems regarding 12 | // cross-compilation. Alternatives such as running a binary to determine the 13 | // value, or trying to derive it in some other way were all problematic. 14 | // After much research it was determined that USER_HZ is actually hardcoded to 15 | // 100 on all Go-supported platforms as of the time of this writing. This is 16 | // why we decided to hardcode it here as well. It is not impossible that there 17 | // could be systems with exceptions, but they should be very exotic edge cases, 18 | // and in that case, the worst outcome will be two misreported metrics. 19 | // 20 | // See also the following discussions: 21 | // 22 | // - https://github.com/prometheus/node_exporter/issues/52 23 | // - https://github.com/prometheus/procfs/pull/2 24 | // - http://stackoverflow.com/questions/17410841/how-does-user-hz-solve-the-jiffy-scaling-issue 25 | const userHZ = 100 26 | 27 | // ProcStat provides status information about the process, 28 | // read from /proc/[pid]/stat. 29 | type ProcStat struct { 30 | // The process ID. 31 | PID int 32 | // The filename of the executable. 33 | Comm string 34 | // The process state. 35 | State string 36 | // The PID of the parent of this process. 37 | PPID int 38 | // The process group ID of the process. 39 | PGRP int 40 | // The session ID of the process. 41 | Session int 42 | // The controlling terminal of the process. 43 | TTY int 44 | // The ID of the foreground process group of the controlling terminal of 45 | // the process. 46 | TPGID int 47 | // The kernel flags word of the process. 48 | Flags uint 49 | // The number of minor faults the process has made which have not required 50 | // loading a memory page from disk. 51 | MinFlt uint 52 | // The number of minor faults that the process's waited-for children have 53 | // made. 54 | CMinFlt uint 55 | // The number of major faults the process has made which have required 56 | // loading a memory page from disk. 57 | MajFlt uint 58 | // The number of major faults that the process's waited-for children have 59 | // made. 60 | CMajFlt uint 61 | // Amount of time that this process has been scheduled in user mode, 62 | // measured in clock ticks. 63 | UTime uint 64 | // Amount of time that this process has been scheduled in kernel mode, 65 | // measured in clock ticks. 66 | STime uint 67 | // Amount of time that this process's waited-for children have been 68 | // scheduled in user mode, measured in clock ticks. 69 | CUTime uint 70 | // Amount of time that this process's waited-for children have been 71 | // scheduled in kernel mode, measured in clock ticks. 72 | CSTime uint 73 | // For processes running a real-time scheduling policy, this is the negated 74 | // scheduling priority, minus one. 75 | Priority int 76 | // The nice value, a value in the range 19 (low priority) to -20 (high 77 | // priority). 78 | Nice int 79 | // Number of threads in this process. 80 | NumThreads int 81 | // The time the process started after system boot, the value is expressed 82 | // in clock ticks. 83 | Starttime uint64 84 | // Virtual memory size in bytes. 85 | VSize int 86 | // Resident set size in pages. 87 | RSS int 88 | 89 | fs FS 90 | } 91 | 92 | // NewStat returns the current status information of the process. 93 | func (p Proc) NewStat() (ProcStat, error) { 94 | f, err := p.open("stat") 95 | if err != nil { 96 | return ProcStat{}, err 97 | } 98 | defer f.Close() 99 | 100 | data, err := ioutil.ReadAll(f) 101 | if err != nil { 102 | return ProcStat{}, err 103 | } 104 | 105 | var ( 106 | ignore int 107 | 108 | s = ProcStat{PID: p.PID, fs: p.fs} 109 | l = bytes.Index(data, []byte("(")) 110 | r = bytes.LastIndex(data, []byte(")")) 111 | ) 112 | 113 | if l < 0 || r < 0 { 114 | return ProcStat{}, fmt.Errorf( 115 | "unexpected format, couldn't extract comm: %s", 116 | data, 117 | ) 118 | } 119 | 120 | s.Comm = string(data[l+1 : r]) 121 | _, err = fmt.Fscan( 122 | bytes.NewBuffer(data[r+2:]), 123 | &s.State, 124 | &s.PPID, 125 | &s.PGRP, 126 | &s.Session, 127 | &s.TTY, 128 | &s.TPGID, 129 | &s.Flags, 130 | &s.MinFlt, 131 | &s.CMinFlt, 132 | &s.MajFlt, 133 | &s.CMajFlt, 134 | &s.UTime, 135 | &s.STime, 136 | &s.CUTime, 137 | &s.CSTime, 138 | &s.Priority, 139 | &s.Nice, 140 | &s.NumThreads, 141 | &ignore, 142 | &s.Starttime, 143 | &s.VSize, 144 | &s.RSS, 145 | ) 146 | if err != nil { 147 | return ProcStat{}, err 148 | } 149 | 150 | return s, nil 151 | } 152 | 153 | // VirtualMemory returns the virtual memory size in bytes. 154 | func (s ProcStat) VirtualMemory() int { 155 | return s.VSize 156 | } 157 | 158 | // ResidentMemory returns the resident memory size in bytes. 159 | func (s ProcStat) ResidentMemory() int { 160 | return s.RSS * os.Getpagesize() 161 | } 162 | 163 | // StartTime returns the unix timestamp of the process in seconds. 164 | func (s ProcStat) StartTime() (float64, error) { 165 | stat, err := s.fs.NewStat() 166 | if err != nil { 167 | return 0, err 168 | } 169 | return float64(stat.BootTime) + (float64(s.Starttime) / userHZ), nil 170 | } 171 | 172 | // CPUTime returns the total CPU user and system time in seconds. 173 | func (s ProcStat) CPUTime() float64 { 174 | return float64(s.UTime+s.STime) / userHZ 175 | } 176 | -------------------------------------------------------------------------------- /procfs/LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------