gupta.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package gupta
  2. import (
  3. "fmt"
  4. "strconv"
  5. "strings"
  6. )
  7. const version = "0.0.1"
  8. func Hello() string {
  9. return fmt.Sprintf("Welcome to gupta version %s", version)
  10. }
  11. func Run(load, cpu, memory bool, partition, networkInterface string) (cpuLoad, cpuUsage, memoryUsage float64) {
  12. cpuLoad = 0.2
  13. cpuUsage = 0.2
  14. memoryUsage = 70.0
  15. return cpuLoad, cpuUsage, memoryUsage
  16. }
  17. type GuptaReport struct {
  18. cpuLoad float64
  19. cpuUsage float64
  20. memoryUsage float64
  21. }
  22. func (g *GuptaReport) GetCPULoad() string {
  23. return fmt.Sprintf("%.2f", g.cpuLoad)
  24. }
  25. // collect all CPU stat from /proc/cpustat
  26. type CPUStat struct {
  27. totalTime float64
  28. idleTime float64
  29. totalTimeNew float64
  30. idleTimeNew float64
  31. }
  32. func (c *CPUStat) ReadInfoNew(statline string) {
  33. rawInfo := strings.Fields(statline)
  34. idleNew, _ := strconv.ParseFloat(rawInfo[4], 10)
  35. iowaitNew, _ := strconv.ParseFloat(rawInfo[5], 10)
  36. c.idleTimeNew = idleNew + iowaitNew
  37. for _, s := range rawInfo {
  38. u, _ := strconv.ParseFloat(s, 10)
  39. c.totalTimeNew += u
  40. }
  41. }
  42. func (c *CPUStat) ReadInfo(statline string) {
  43. rawInfo := strings.Fields(statline)
  44. for _, s := range rawInfo[1:] {
  45. u, _ := strconv.ParseFloat(s, 10)
  46. c.totalTime += u
  47. }
  48. idle, _ := strconv.ParseFloat(rawInfo[4], 10)
  49. iowait, _ := strconv.ParseFloat(rawInfo[5], 10)
  50. c.idleTime = idle + iowait
  51. }
  52. func (c *CPUStat) CPUUsage() float64 {
  53. deltaIdleTime := c.idleTimeNew - c.idleTime
  54. deltaTotalTime := c.totalTimeNew - c.totalTime
  55. cpuUsage := (1.0 - float64(deltaIdleTime)/float64(deltaTotalTime)) * 100
  56. return cpuUsage
  57. }
  58. func NewCPUStat(procstatline, procstatlineNew string) CPUStat {
  59. cpustat := CPUStat{}
  60. cpustat.ReadInfo(procstatline)
  61. cpustat.ReadInfoNew(procstatlineNew)
  62. return cpustat
  63. }