Skip to content

Commit

Permalink
add cpu usage functions (#653)
Browse files Browse the repository at this point in the history
  • Loading branch information
frostbyte73 authored Apr 16, 2024
1 parent 3bc566b commit b9cecd7
Showing 1 changed file with 38 additions and 26 deletions.
64 changes: 38 additions & 26 deletions pkg/stats/monitor.go
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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()
Expand Down

0 comments on commit b9cecd7

Please sign in to comment.