-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
84 lines (76 loc) · 1.89 KB
/
main.go
File metadata and controls
84 lines (76 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package main
import (
"encoding/json"
"log"
"net/http"
"sync"
)
type Device struct {
Index int `json:"index"`
UUID string `json:"uuid"`
Memory float64 `json:"memory"` // used
Total float64 `json:"total"`
}
type Summary struct {
TotalGPUs int `json:"total_gpus"`
TotalUsedMem float64 `json:"total_used_mem"`
TotalFreeMem float64 `json:"total_free_mem"`
AverageFreeMem float64 `json:"avg_free_mem_per_gpu"`
}
var (
mu sync.RWMutex
store = make(map[string][]Device)
)
func handleDump(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
var data map[string][]Device
if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
http.Error(w, "invalid JSON", http.StatusBadRequest)
return
}
mu.Lock()
for host, devs := range data {
store[host] = devs
}
mu.Unlock()
w.WriteHeader(http.StatusNoContent)
}
func handleGetAll(w http.ResponseWriter, r *http.Request) {
mu.RLock()
defer mu.RUnlock()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(store)
}
func handleSummary(w http.ResponseWriter, r *http.Request) {
mu.RLock()
defer mu.RUnlock()
out := make(map[string]Summary)
for host, devs := range store {
var used, total float64
for _, d := range devs {
used += d.Memory
total += d.Total
}
free := total - used
count := len(devs)
avgFree := 0.0
if count > 0 {
avgFree = free / float64(count)
}
out[host] = Summary{
TotalGPUs: count,
TotalUsedMem: used,
TotalFreeMem: free,
AverageFreeMem: avgFree,
}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(out)
}
func main() {
http.HandleFunc("/dump", handleDump) // POST JSON dump here
http.HandleFunc("/devices", handleGetAll) // GET full map
http.HandleFunc("/summary", handleSummary) // GET per-host summary
log.Println("listening on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}