waveterm/pkg/wshrpc/wshremote/sysinfo.go

70 lines
1.7 KiB
Go
Raw Normal View History

2024-08-30 20:33:04 +02:00
// Copyright 2024, Command Line Inc.
// SPDX-License-Identifier: Apache-2.0
package wshremote
import (
"log"
"strconv"
"time"
"github.com/shirou/gopsutil/v4/cpu"
"github.com/shirou/gopsutil/v4/mem"
"github.com/wavetermdev/thenextwave/pkg/wshrpc"
"github.com/wavetermdev/thenextwave/pkg/wshrpc/wshclient"
"github.com/wavetermdev/thenextwave/pkg/wshutil"
)
func getCpuData(values map[string]float64) {
percentArr, err := cpu.Percent(0, false)
if err != nil {
return
}
if len(percentArr) > 0 {
values[wshrpc.TimeSeries_Cpu] = percentArr[0]
}
percentArr, err = cpu.Percent(0, true)
if err != nil {
return
}
for idx, percent := range percentArr {
values[wshrpc.TimeSeries_Cpu+":"+strconv.Itoa(idx)] = percent
}
}
func getMemData(values map[string]float64) {
memData, err := mem.VirtualMemory()
if err != nil {
return
}
values["mem:total"] = float64(memData.Total)
values["mem:available"] = float64(memData.Available)
values["mem:used"] = float64(memData.Used)
values["mem:free"] = float64(memData.Free)
}
func generateSingleServerData(client *wshutil.WshRpc, connName string) {
now := time.Now()
values := make(map[string]float64)
getCpuData(values)
getMemData(values)
tsData := wshrpc.TimeSeriesData{Ts: now.UnixMilli(), Values: values}
event := wshrpc.WaveEvent{
Event: wshrpc.Event_SysInfo,
Scopes: []string{connName},
Data: tsData,
Persist: 1024,
}
wshclient.EventPublishCommand(client, event, &wshrpc.RpcOpts{NoResponse: true})
}
func RunSysInfoLoop(client *wshutil.WshRpc, connName string) {
defer func() {
log.Printf("sysinfo loop ended conn:%s\n", connName)
}()
for {
generateSingleServerData(client, connName)
time.Sleep(1 * time.Second)
}
}