gupta.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package gupta
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "strconv"
  6. "strings"
  7. "time"
  8. )
  9. const version = "0.0.1"
  10. func Hello() string {
  11. return fmt.Sprintf("Welcome to gupta version %s", version)
  12. }
  13. type GuptaReport struct {
  14. Time time.Time
  15. LoadAvarage float64
  16. CPUUsage *CPUStat `json:"cpu usage, omitempty"`
  17. MemoryUsage *Memory `json:"memory,omitempty"`
  18. }
  19. // usually you'd want a g GuptaReport reciever here ...
  20. // but than you could now check for the object properties ...
  21. func (g *GuptaReport) MarshalJSON() ([]byte, error) {
  22. report := []byte(fmt.Sprintf("{\"timestamp\": \"%d\", \"metrics\": [",
  23. g.Time.Unix()))
  24. if g.CPUUsage != nil {
  25. usage, _ := json.Marshal(g.CPUUsage)
  26. report = append(report, usage...)
  27. }
  28. if g.MemoryUsage != nil {
  29. if g.CPUUsage != nil {
  30. report = append(report, []byte(",")...)
  31. }
  32. usage, _ := json.Marshal(g.MemoryUsage)
  33. report = append(report, usage...)
  34. }
  35. report = append(report, []byte("]}")...)
  36. return report, nil
  37. }
  38. // collect all CPU stat from /proc/cpustat
  39. type CPUStat struct {
  40. totalTime float64
  41. idleTime float64
  42. totalTimeNew float64
  43. idleTimeNew float64
  44. }
  45. func (c *CPUStat) ReadInfoNew(statline string) {
  46. rawInfo := strings.Fields(statline)
  47. idleNew, _ := strconv.ParseFloat(rawInfo[4], 10)
  48. iowaitNew, _ := strconv.ParseFloat(rawInfo[5], 10)
  49. c.idleTimeNew = idleNew + iowaitNew
  50. for _, s := range rawInfo {
  51. u, _ := strconv.ParseFloat(s, 10)
  52. c.totalTimeNew += u
  53. }
  54. }
  55. func (c *CPUStat) ReadInfo(statline string) {
  56. rawInfo := strings.Fields(statline)
  57. for _, s := range rawInfo[1:] {
  58. u, _ := strconv.ParseFloat(s, 10)
  59. c.totalTime += u
  60. }
  61. idle, _ := strconv.ParseFloat(rawInfo[4], 10)
  62. iowait, _ := strconv.ParseFloat(rawInfo[5], 10)
  63. c.idleTime = idle + iowait
  64. }
  65. func (c *CPUStat) CPUUsage() float64 {
  66. deltaIdleTime := c.idleTimeNew - c.idleTime
  67. deltaTotalTime := c.totalTimeNew - c.totalTime
  68. cpuUsage := (1.0 - float64(deltaIdleTime)/float64(deltaTotalTime)) * 100
  69. return cpuUsage
  70. }
  71. func NewCPUStat(procstatline, procstatlineNew string) CPUStat {
  72. cpustat := CPUStat{}
  73. cpustat.ReadInfo(procstatline)
  74. cpustat.ReadInfoNew(procstatlineNew)
  75. return cpustat
  76. }
  77. func (c CPUStat) MarshalJSON() ([]byte, error) {
  78. jsonData := []byte(
  79. fmt.Sprintf("{\"cpu usage\": \"%.2f%%\"}", c.CPUUsage()))
  80. return jsonData, nil
  81. }