analytic.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package analytic
  2. import (
  3. "github.com/uozi-tech/cosy/logger"
  4. "github.com/shirou/gopsutil/v3/net"
  5. "time"
  6. )
  7. type Usage[T uint64 | float64] struct {
  8. Time time.Time `json:"x"`
  9. Usage T `json:"y"`
  10. }
  11. var (
  12. CpuUserRecord []Usage[float64]
  13. CpuTotalRecord []Usage[float64]
  14. NetRecvRecord []Usage[uint64]
  15. NetSentRecord []Usage[uint64]
  16. DiskWriteRecord []Usage[uint64]
  17. DiskReadRecord []Usage[uint64]
  18. LastDiskWrites uint64
  19. LastDiskReads uint64
  20. LastNetSent uint64
  21. LastNetRecv uint64
  22. )
  23. func init() {
  24. network, _ := net.IOCounters(false)
  25. if len(network) > 0 {
  26. LastNetRecv = network[0].BytesRecv
  27. LastNetSent = network[0].BytesSent
  28. }
  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. }