forked from cloudfoundry/gorouter
/
process_status.go
62 lines (51 loc) · 1016 Bytes
/
process_status.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package common
import (
"sync"
"syscall"
"time"
)
const RefreshInterval time.Duration = time.Second * 1
type ProcessStatus struct {
sync.Mutex
rusage *syscall.Rusage
lastCpuTime int64
stopSignal chan bool
stopped bool
CpuUsage float64
MemRss int64
}
func NewProcessStatus() *ProcessStatus {
p := new(ProcessStatus)
p.rusage = new(syscall.Rusage)
go func() {
timer := time.Tick(RefreshInterval)
for {
select {
case <-timer:
p.Update()
case <-p.stopSignal:
return
}
}
}()
return p
}
func (p *ProcessStatus) Update() {
e := syscall.Getrusage(syscall.RUSAGE_SELF, p.rusage)
if e != nil {
log.Fatal(e.Error())
}
p.MemRss = int64(p.rusage.Maxrss)
t := p.rusage.Utime.Nano() + p.rusage.Stime.Nano()
p.CpuUsage = float64(t-p.lastCpuTime) / float64(RefreshInterval.Nanoseconds())
p.lastCpuTime = t
}
func (p *ProcessStatus) StopUpdate() {
p.Lock()
defer p.Unlock()
if !p.stopped {
p.stopped = true
p.stopSignal <- true
p.stopSignal = nil
}
}