analytic.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package analytic
  2. import (
  3. "time"
  4. "github.com/uozi-tech/cosy/logger"
  5. )
  6. type Usage[T uint64 | float64] struct {
  7. Time time.Time `json:"x"`
  8. Usage T `json:"y"`
  9. }
  10. var (
  11. CpuUserRecord []Usage[float64]
  12. CpuTotalRecord []Usage[float64]
  13. NetRecvRecord []Usage[uint64]
  14. NetSentRecord []Usage[uint64]
  15. DiskWriteRecord []Usage[uint64]
  16. DiskReadRecord []Usage[uint64]
  17. LastDiskWrites uint64
  18. LastDiskReads uint64
  19. LastNetSent uint64
  20. LastNetRecv uint64
  21. )
  22. func init() {
  23. network, err := GetNetworkStat()
  24. if err != nil {
  25. logger.Error(err)
  26. }
  27. LastNetRecv = network.BytesRecv
  28. LastNetSent = network.BytesSent
  29. LastDiskReads, LastDiskWrites = getTotalDiskIO()
  30. now := time.Now()
  31. // init record slices
  32. for i := 100; i > 0; i-- {
  33. uf := Usage[float64]{Time: now.Add(time.Duration(-i) * time.Second), Usage: 0}
  34. CpuUserRecord = append(CpuUserRecord, uf)
  35. CpuTotalRecord = append(CpuTotalRecord, uf)
  36. u := Usage[uint64]{Time: now.Add(time.Duration(-i) * time.Second), Usage: 0}
  37. NetRecvRecord = append(NetRecvRecord, u)
  38. NetSentRecord = append(NetSentRecord, u)
  39. DiskWriteRecord = append(DiskWriteRecord, u)
  40. DiskReadRecord = append(DiskReadRecord, u)
  41. }
  42. }
  43. func RecordServerAnalytic() {
  44. logger.Info("RecordServerAnalytic Started")
  45. for {
  46. now := time.Now()
  47. recordCpu(now) // this func will spend more than 1 second.
  48. recordNetwork(now)
  49. recordDiskIO(now)
  50. }
  51. }