github.com/ssetin/penguincast@v0.2.0/src/server/monitor.go (about) 1 // Package iceserver - icecast streaming server 2 package iceserver 3 4 import ( 5 "encoding/json" 6 "fmt" 7 "math" 8 "net/http" 9 "sync/atomic" 10 "time" 11 12 "github.com/gorilla/websocket" 13 ) 14 15 //MonitorInfo ... 16 type MonitorInfo struct { 17 Mounts []MountInfo 18 CPUUsage float64 19 MemUsage int 20 } 21 22 var upgrader = websocket.Upgrader{ 23 ReadBufferSize: 1024, 24 WriteBufferSize: 1024, 25 CheckOrigin: func(r *http.Request) bool { 26 return true 27 }, 28 } 29 30 func (i *IceServer) processStats() { 31 ticker := time.NewTicker(3 * time.Second) 32 for { 33 CPU, Memory, err := i.statReader.GetCPUAndMem() 34 if err != nil { 35 i.printError(1, err.Error()) 36 ticker.Stop() 37 break 38 } 39 fmt.Fprintf(i.statFile, time.Now().Format("2006-01-02 15:04:05")+"\t%d\t%f\t%d\n", atomic.LoadInt32(&i.ListenersCount), CPU, Memory/1024) 40 i.mux.Lock() 41 i.cpuUsage = math.Floor(CPU*100) / 100 42 i.memUsage = Memory / 1024 43 i.mux.Unlock() 44 <-ticker.C 45 } 46 } 47 48 func (i *IceServer) sendMonitorInfo(client *websocket.Conn) { 49 ticker := time.NewTicker(5 * time.Second) 50 for { 51 w, err := client.NextWriter(websocket.TextMessage) 52 if err != nil { 53 ticker.Stop() 54 break 55 } 56 57 monitorInfo := &MonitorInfo{} 58 monitorInfo.Mounts = make([]MountInfo, 0, len(i.Props.Mounts)) 59 60 for idx := range i.Props.Mounts { 61 inf := i.Props.Mounts[idx].getMountsInfo() 62 monitorInfo.Mounts = append(monitorInfo.Mounts, inf) 63 } 64 i.mux.Lock() 65 monitorInfo.CPUUsage = i.cpuUsage 66 monitorInfo.MemUsage = i.memUsage 67 i.mux.Unlock() 68 69 msg, _ := json.Marshal(monitorInfo) 70 w.Write(msg) 71 w.Close() 72 73 <-ticker.C 74 } 75 }