Maybe fix sleep time and add it to status page

This commit is contained in:
Sebastiaan de Schaetzen 2025-03-30 14:47:01 +02:00
parent bccc177374
commit 7cfcfa330c

38
main.go
View File

@ -23,14 +23,13 @@ import (
)
const (
checkInterval = 10 * time.Second
monitoringPeriod = 5 * time.Minute
resumeGracePeriod = 5 * time.Minute // Time to wait after resume before allowing sleep again
cpuThreshold = 20.0 // percentage
gpuThreshold = 20.0 // percentage
diskThreshold = 5 * 1024 * 1024 // 5 MB/s
networkThreshold = 1 * 1024 * 1024 // 1 MB/s
httpPort = 8081
checkInterval = 10 * time.Second
monitoringPeriod = 5 * time.Minute
cpuThreshold = 20.0 // percentage
gpuThreshold = 20.0 // percentage
diskThreshold = 5 * 1024 * 1024 // 5 MB/s
networkThreshold = 1 * 1024 * 1024 // 1 MB/s
httpPort = 8081
)
type ResourceUsage struct {
@ -48,16 +47,17 @@ type StatusResponse struct {
Usage ResourceUsage `json:"usage"`
Blockers []string `json:"blockers"`
Timestamp time.Time `json:"timestamp"`
SleepAt time.Time `json:"sleep_at"`
}
var (
statusMutex sync.RWMutex
blockers []string
currentStatus ResourceUsage
nvmlAvailable bool
networkBytesIO uint64
diskBytesIO uint64
lastBlockedTime time.Time
statusMutex sync.RWMutex
blockers []string
currentStatus ResourceUsage
nvmlAvailable bool
networkBytesIO uint64
diskBytesIO uint64
nextSleepTime time.Time
)
func Must(err error) {
@ -105,7 +105,6 @@ func main() {
log.Printf("- No active SSH connections\n")
log.Printf("- No active user sessions\n")
log.Printf("- Over the last %v\n", monitoringPeriod)
log.Printf("- System will not suspend for %v after resuming from sleep\n", resumeGracePeriod)
log.Printf("HTTP status endpoint available at http://localhost:%d/status\n", httpPort)
log.Printf("Press Ctrl+C to exit\n")
@ -119,7 +118,7 @@ mainLoop:
updateCurrentUsage()
updateSystemStatus()
if time.Now().Sub(lastBlockedTime) >= monitoringPeriod {
if time.Now().After(nextSleepTime) {
log.Printf("System status before suspend:\n")
log.Printf("- CPU: %.1f%%\n", usageHistory[len(usageHistory)-1].CpuUsage)
if nvmlAvailable {
@ -131,7 +130,7 @@ mainLoop:
if err := suspendSystem(); err != nil {
log.Printf("Failed to suspend system: %v", err)
}
lastBlockedTime = time.Now()
nextSleepTime = time.Now().Add(monitoringPeriod)
log.Printf("Resumed")
}
}
@ -172,6 +171,7 @@ func handleStatus(w http.ResponseWriter, _ *http.Request) {
Usage: currentStatus,
Blockers: blockers,
Timestamp: time.Now(),
SleepAt: nextSleepTime,
}
w.Header().Set("Content-Type", "application/json")
@ -218,7 +218,7 @@ func updateSystemStatus() {
if len(blockers) == 0 {
blockers = append(blockers, "No blockers - system can sleep")
} else {
lastBlockedTime = time.Now()
nextSleepTime = time.Now().Add(monitoringPeriod)
}
}