analytic.go 1.5 KB

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