Path: blob/main/components/ws-daemon/pkg/cpulimit/bandwidth.go
2500 views
// Copyright (c) 2022 Gitpod GmbH. All rights reserved.1// Licensed under the GNU Affero General Public License (AGPL).2// See License.AGPL.txt in the project root for license information.34package cpulimit56import (7"fmt"8"time"910"k8s.io/apimachinery/pkg/api/resource"11)1213// Bandwidth represents the bandwidth of a CPU as milliseconds of CPU time per second.14// For example: 6000 CPU ms / second is the equivalent of 6 CPUs.15type Bandwidth uint641617// BandwidthFromQuotaAndPeriod converts quota and period (e.g. from Linux CFS bandwidth controller)18// to our own CPU bandwidth representation.19func BandwidthFromQuotaAndPeriod(quota, period time.Duration) Bandwidth {20if period == 0 {21return 022}2324// we divide on the micro/milli level rather than milli/seconds to avoid floating point math.25res := quota.Microseconds() / period.Milliseconds()26return Bandwidth(res)27}2829// BandwidthFromQuantity converts a quantity to CPU bandwidth.30func BandwidthFromQuantity(v resource.Quantity) Bandwidth {31return Bandwidth(v.MilliValue())32}3334// BandwithFromUsage computes the bandwidth neccesary to realise actual CPU time35// consumption represented by two point samples.36func BandwithFromUsage(t0, t1 CPUTime, dt time.Duration) (Bandwidth, error) {37if dt == 0 {38return 0, nil39}40if t1 < t0 {41return 0, fmt.Errorf("usage cannot be negative")42}4344// we divide on the micro/milli level rather than milli/seconds to avoid floating point math.45res := time.Duration(t1-t0).Microseconds() / dt.Milliseconds()46return Bandwidth(res), nil47}4849// Quota expresses the bandwidth as quota with respect to the period.50// This is useful when writing the quota of a CFS bandwidth controller.51func (b Bandwidth) Quota(period time.Duration) time.Duration {52return time.Duration((time.Duration(b) * time.Millisecond).Microseconds() * period.Milliseconds())53}5455// Integrate returns the total CPU time used if the bandwidth is exhausted56// for the given period of time.57func (b Bandwidth) Integrate(dt time.Duration) CPUTime {58return CPUTime(time.Duration(b) * time.Microsecond * time.Duration(dt.Milliseconds()))59}6061// CPUTime describes actual CPU time used62type CPUTime time.Duration636465