gupta.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. user uint64
  28. nice uint64
  29. system uint64
  30. idle uint64
  31. iowait uint64
  32. irq uint64
  33. softirq uint64
  34. steal uint64
  35. guest uint64
  36. guest_nice uint64
  37. }
  38. // parse the first line of /proc/cpustat
  39. func (c *CPUStat) ReadInfo(rawInfo []string) {
  40. if s, err := strconv.ParseUint(rawInfo[0], 10, 64); err == nil {
  41. c.user = s
  42. }
  43. if s, err := strconv.ParseUint(rawInfo[1], 10, 64); err == nil {
  44. c.nice = s
  45. }
  46. if s, err := strconv.ParseUint(rawInfo[2], 10, 64); err == nil {
  47. c.system = s
  48. }
  49. if s, err := strconv.ParseUint(rawInfo[3], 10, 64); err == nil {
  50. c.idle = s
  51. }
  52. if s, err := strconv.ParseUint(rawInfo[4], 10, 64); err == nil {
  53. c.iowait = s
  54. }
  55. if s, err := strconv.ParseUint(rawInfo[5], 10, 64); err == nil {
  56. c.irq = s
  57. }
  58. if s, err := strconv.ParseUint(rawInfo[6], 10, 64); err == nil {
  59. c.softirq = s
  60. }
  61. if s, err := strconv.ParseUint(rawInfo[7], 10, 64); err == nil {
  62. c.steal = s
  63. }
  64. if s, err := strconv.ParseUint(rawInfo[8], 10, 64); err == nil {
  65. c.guest = s
  66. }
  67. if s, err := strconv.ParseUint(rawInfo[9], 10, 64); err == nil {
  68. c.guest_nice = s
  69. }
  70. }
  71. func (c *CPUStat) TotalTime() uint64 {
  72. return c.user + c.nice + c.system + c.idle + c.iowait + c.irq + c.softirq + c.steal
  73. }
  74. func (c *CPUStat) IdleTime() uint64 {
  75. return c.idle + c.iowait
  76. }
  77. func (c *CPUStat) CPUUsage() uint64 {
  78. return c.TotalTime() - c.IdleTime()
  79. }
  80. func NewCPUStat(procstatline string) CPUStat {
  81. cpustat := CPUStat{}
  82. statline := strings.Fields(procstatline)
  83. cpustat.ReadInfo(statline[1:])
  84. return cpustat
  85. }