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