system.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package system
  2. // for retrieving hw info and managing host
  3. import (
  4. "fmt"
  5. "github.com/shirou/gopsutil/cpu"
  6. "github.com/shirou/gopsutil/disk"
  7. "github.com/shirou/gopsutil/mem"
  8. "goseg/config"
  9. "io/ioutil"
  10. "strconv"
  11. "strings"
  12. "time"
  13. )
  14. // get memory used/avail in bytes
  15. func GetMemory() (uint64, uint64) {
  16. v, _ := mem.VirtualMemory()
  17. return v.Used, v.Total
  18. }
  19. // get cpu usage as %
  20. func GetCPU() int {
  21. percent, _ := cpu.Percent(time.Second, false)
  22. return int(percent[0])
  23. }
  24. // get used/avail disk in bytes
  25. func GetDisk() (uint64, uint64) {
  26. d, _ := disk.Usage("/")
  27. return d.Used, d.Free
  28. }
  29. // get cpu temp (may not work on some devices)
  30. func GetTemp() float64 {
  31. data, err := ioutil.ReadFile("/sys/class/thermal/thermal_zone0/temp")
  32. if err != nil {
  33. errmsg := fmt.Sprintf("Error reading temperature:", err)
  34. config.Logger.Error(errmsg)
  35. return 0
  36. }
  37. tempStr := strings.TrimSpace(string(data))
  38. temp, err := strconv.Atoi(tempStr)
  39. if err != nil {
  40. errmsg := fmt.Sprintf("Error converting temperature to integer:", err)
  41. config.Logger.Error(errmsg)
  42. return 0
  43. }
  44. return float64(temp) / 1000.0
  45. }
  46. // return 0 for no 1 for yes(?)
  47. func HasSwap() int {
  48. data, err := ioutil.ReadFile("/proc/swaps")
  49. if err != nil {
  50. errmsg := fmt.Sprintf("Error reading swap status:", err)
  51. config.Logger.Error(errmsg)
  52. return 0
  53. }
  54. lines := strings.Split(string(data), "\n")
  55. if len(lines) > 1 {
  56. return 1
  57. } else {
  58. return 0
  59. }
  60. }