Rework block detection

This commit is contained in:
Sebastiaan de Schaetzen 2025-04-09 10:22:57 +02:00
parent cc20e1c09a
commit ad0feb756f

25
main.go
View File

@ -41,6 +41,7 @@ type ResourceUsage struct {
NetworkIO float64 `json:"network_io"`
SshConnections int `json:"ssh_connections"`
ActiveUsers int `json:"active_users"`
HttpRequests int `json:"http_requests"`
}
type StatusResponse struct {
@ -52,7 +53,6 @@ type StatusResponse struct {
var (
statusMutex sync.RWMutex
blockers []string
currentStatus ResourceUsage
nvmlAvailable bool
networkBytesIO uint64
@ -109,7 +109,10 @@ mainLoop:
break mainLoop
case <-ticker.C:
updateCurrentUsage()
updateSystemStatus()
blocked, _ := getBlockers()
if blocked {
nextSleepTime = time.Now().Add(monitoringPeriod)
}
if time.Now().After(nextSleepTime) {
log.Printf("System status before suspend:\n")
@ -163,6 +166,8 @@ func handleStatus(w http.ResponseWriter, _ *http.Request) {
statusMutex.RLock()
defer statusMutex.RUnlock()
_, blockers := getBlockers()
response := StatusResponse{
Usage: currentStatus,
Blockers: blockers,
@ -181,16 +186,17 @@ func handleReset(w http.ResponseWriter, _ *http.Request) {
statusMutex.Lock()
defer statusMutex.Unlock()
currentStatus.HttpRequests++
nextSleepTime = time.Now().Add(monitoringPeriod)
blockers = []string{"blocked by HTTP"}
w.WriteHeader(http.StatusOK)
}
func updateSystemStatus() {
func getBlockers() (bool, []string) {
statusMutex.Lock()
defer statusMutex.Unlock()
blockers = []string{}
blocked := true
blockers := []string{}
if currentStatus.CpuUsage >= cpuThreshold {
blockers = append(blockers,
@ -220,11 +226,16 @@ func updateSystemStatus() {
fmt.Sprintf("Active user sessions: %d", currentStatus.ActiveUsers))
}
if currentStatus.HttpRequests > 0 {
blockers = append(blockers,
fmt.Sprintf("HTTP requests received: %d", currentStatus.HttpRequests))
}
if len(blockers) == 0 {
blockers = append(blockers, "No blockers - system can sleep")
} else {
nextSleepTime = time.Now().Add(monitoringPeriod)
blocked = false
}
return blocked, blockers
}
func updateCurrentUsage() {