From b1561ca61c0b21afccbe2809694b3b4e183cdf35 Mon Sep 17 00:00:00 2001 From: David Colburn Date: Mon, 15 Apr 2024 18:20:32 -0700 Subject: [PATCH] add cpu usage functions --- pkg/stats/monitor.go | 64 ++++++++++++++++++++++++++------------------ 1 file changed, 38 insertions(+), 26 deletions(-) diff --git a/pkg/stats/monitor.go b/pkg/stats/monitor.go index 8db37128..98d36fa6 100644 --- a/pkg/stats/monitor.go +++ b/pkg/stats/monitor.go @@ -253,33 +253,9 @@ func (m *Monitor) CanAcceptRequest(req *rpc.StartEgressRequest) bool { } func (m *Monitor) canAcceptRequestLocked(req *rpc.StartEgressRequest) bool { - accept := false - total := m.cpuStats.NumCPU() - - var available, pending, used float64 - if m.requests.Load() == 0 { - // if no requests, use total - available = total - } else { - for _, ps := range m.pending { - if ps.pendingUsage > ps.lastUsage { - pending += ps.pendingUsage - } else { - pending += ps.lastUsage - } - } - for _, ps := range m.procStats { - if ps.pendingUsage > ps.lastUsage { - used += ps.pendingUsage - } else { - used += ps.lastUsage - } - } - - // if already running requests, cap usage at MaxCpuUtilization - available = total*m.cpuCostConfig.MaxCpuUtilization - pending - used - } + total, available, pending, used := m.getCPUUsageLocked() + var accept bool var required float64 switch r := req.Request.(type) { case *rpc.StartEgressRequest_RoomComposite: @@ -316,6 +292,42 @@ func (m *Monitor) canAcceptRequestLocked(req *rpc.StartEgressRequest) bool { return accept } +func (m *Monitor) GetAvailableCPU() float64 { + m.mu.Lock() + defer m.mu.Unlock() + + _, available, _, _ := m.getCPUUsageLocked() + return available +} + +func (m *Monitor) getCPUUsageLocked() (total, available, pending, used float64) { + total = m.cpuStats.NumCPU() + if m.requests.Load() == 0 { + // if no requests, use total + available = total + return + } + + for _, ps := range m.pending { + if ps.pendingUsage > ps.lastUsage { + pending += ps.pendingUsage + } else { + pending += ps.lastUsage + } + } + for _, ps := range m.procStats { + if ps.pendingUsage > ps.lastUsage { + used += ps.pendingUsage + } else { + used += ps.lastUsage + } + } + + // if already running requests, cap usage at MaxCpuUtilization + available = total*m.cpuCostConfig.MaxCpuUtilization - pending - used + return +} + func (m *Monitor) AcceptRequest(req *rpc.StartEgressRequest) error { m.mu.Lock() defer m.mu.Unlock()