forked from Cloud-Foundations/Dominator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
limiter.go
78 lines (71 loc) · 1.84 KB
/
limiter.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package cpulimiter
import (
"runtime"
"time"
"github.com/Cloud-Foundations/Dominator/lib/wsyscall"
)
var minCheckInterval = time.Millisecond * 10
func newCpuLimiter(cpuPercent uint) *CpuLimiter {
cl := new(CpuLimiter)
cl.setCpuPercent(cpuPercent)
return cl
}
func (cl *CpuLimiter) getConfCpuPercent() uint {
cl.mutex.Lock()
defer cl.mutex.Unlock()
return cl.confCpuPercent
}
func (cl *CpuLimiter) limit() error {
cl.mutex.Lock()
defer cl.mutex.Unlock()
if cl.cpuPercent >= 100 {
return nil
}
now := time.Now()
if cl.lastProbeTime.IsZero() { // Initialise.
var rusage wsyscall.Rusage
err := wsyscall.Getrusage(wsyscall.RUSAGE_THREAD, &rusage)
if err != nil {
return err
}
cl.lastProbeTime = now
cl.lastProbeCpuTime = rusage.Utime
return nil
}
wallTimeSinceLastProbe := now.Sub(cl.lastProbeTime)
if wallTimeSinceLastProbe < minCheckInterval {
return nil
}
var rusage wsyscall.Rusage
if err := wsyscall.Getrusage(wsyscall.RUSAGE_THREAD, &rusage); err != nil {
return err
}
cpuTimeSinceLastProbe := time.Duration(rusage.Utime.Sec-
cl.lastProbeCpuTime.Sec) * time.Second
cpuTimeSinceLastProbe += time.Duration(
rusage.Utime.Usec-cl.lastProbeCpuTime.Usec) * time.Microsecond
sleepTime := cpuTimeSinceLastProbe*100/time.Duration(cl.cpuPercent) -
wallTimeSinceLastProbe
cl.mutex.Unlock()
time.Sleep(sleepTime)
cl.mutex.Lock()
cl.lastProbeTime = time.Now()
cl.lastProbeCpuTime = rusage.Utime
return nil
}
func (cl *CpuLimiter) setCpuPercent(cpuPercent uint) {
if cpuPercent < 1 {
cpuPercent = 1
} else if cpuPercent > 100 {
cpuPercent = 100
}
singleCpuPercent := cpuPercent * uint(runtime.NumCPU())
if singleCpuPercent > 100 {
singleCpuPercent = 100
}
cl.mutex.Lock()
defer cl.mutex.Unlock()
cl.confCpuPercent = cpuPercent
cl.cpuPercent = singleCpuPercent
cl.lastProbeTime = time.Time{} // Reset calculations.
}