Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/ws-daemon/pkg/cpulimit/bandwidth.go
2500 views
1
// Copyright (c) 2022 Gitpod GmbH. All rights reserved.
2
// Licensed under the GNU Affero General Public License (AGPL).
3
// See License.AGPL.txt in the project root for license information.
4
5
package cpulimit
6
7
import (
8
"fmt"
9
"time"
10
11
"k8s.io/apimachinery/pkg/api/resource"
12
)
13
14
// Bandwidth represents the bandwidth of a CPU as milliseconds of CPU time per second.
15
// For example: 6000 CPU ms / second is the equivalent of 6 CPUs.
16
type Bandwidth uint64
17
18
// BandwidthFromQuotaAndPeriod converts quota and period (e.g. from Linux CFS bandwidth controller)
19
// to our own CPU bandwidth representation.
20
func BandwidthFromQuotaAndPeriod(quota, period time.Duration) Bandwidth {
21
if period == 0 {
22
return 0
23
}
24
25
// we divide on the micro/milli level rather than milli/seconds to avoid floating point math.
26
res := quota.Microseconds() / period.Milliseconds()
27
return Bandwidth(res)
28
}
29
30
// BandwidthFromQuantity converts a quantity to CPU bandwidth.
31
func BandwidthFromQuantity(v resource.Quantity) Bandwidth {
32
return Bandwidth(v.MilliValue())
33
}
34
35
// BandwithFromUsage computes the bandwidth neccesary to realise actual CPU time
36
// consumption represented by two point samples.
37
func BandwithFromUsage(t0, t1 CPUTime, dt time.Duration) (Bandwidth, error) {
38
if dt == 0 {
39
return 0, nil
40
}
41
if t1 < t0 {
42
return 0, fmt.Errorf("usage cannot be negative")
43
}
44
45
// we divide on the micro/milli level rather than milli/seconds to avoid floating point math.
46
res := time.Duration(t1-t0).Microseconds() / dt.Milliseconds()
47
return Bandwidth(res), nil
48
}
49
50
// Quota expresses the bandwidth as quota with respect to the period.
51
// This is useful when writing the quota of a CFS bandwidth controller.
52
func (b Bandwidth) Quota(period time.Duration) time.Duration {
53
return time.Duration((time.Duration(b) * time.Millisecond).Microseconds() * period.Milliseconds())
54
}
55
56
// Integrate returns the total CPU time used if the bandwidth is exhausted
57
// for the given period of time.
58
func (b Bandwidth) Integrate(dt time.Duration) CPUTime {
59
return CPUTime(time.Duration(b) * time.Microsecond * time.Duration(dt.Milliseconds()))
60
}
61
62
// CPUTime describes actual CPU time used
63
type CPUTime time.Duration
64
65