analytic.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package analytic
  2. import (
  3. "github.com/shirou/gopsutil/v4/net"
  4. "github.com/uozi-tech/cosy/logger"
  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, err := net.IOCounters(false)
  25. if err != nil {
  26. logger.Error(err)
  27. }
  28. if len(network) > 0 {
  29. LastNetRecv = network[0].BytesRecv
  30. LastNetSent = network[0].BytesSent
  31. }
  32. LastDiskReads, LastDiskWrites = getTotalDiskIO()
  33. now := time.Now()
  34. // init record slices
  35. for i := 100; i > 0; i-- {
  36. uf := Usage[float64]{Time: now.Add(time.Duration(-i) * time.Second), Usage: 0}
  37. CpuUserRecord = append(CpuUserRecord, uf)
  38. CpuTotalRecord = append(CpuTotalRecord, uf)
  39. u := Usage[uint64]{Time: now.Add(time.Duration(-i) * time.Second), Usage: 0}
  40. NetRecvRecord = append(NetRecvRecord, u)
  41. NetSentRecord = append(NetSentRecord, u)
  42. DiskWriteRecord = append(DiskWriteRecord, u)
  43. DiskReadRecord = append(DiskReadRecord, u)
  44. }
  45. }
  46. func RecordServerAnalytic() {
  47. logger.Info("RecordServerAnalytic Started")
  48. for {
  49. now := time.Now()
  50. recordCpu(now) // this func will spend more than 1 second.
  51. recordNetwork(now)
  52. recordDiskIO(now)
  53. }
  54. }