analytic.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package analytic
  2. import (
  3. "github.com/0xJacky/Nginx-UI/server/internal/logger"
  4. "github.com/shirou/gopsutil/v3/net"
  5. "time"
  6. )
  7. type Usage struct {
  8. Time time.Time `json:"x"`
  9. Usage interface{} `json:"y"`
  10. }
  11. var (
  12. CpuUserRecord []Usage
  13. CpuTotalRecord []Usage
  14. NetRecvRecord []Usage
  15. NetSentRecord []Usage
  16. DiskWriteRecord []Usage
  17. DiskReadRecord []Usage
  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. u := Usage{Time: now.Add(time.Duration(-i) * time.Second), Usage: 0}
  34. CpuUserRecord = append(CpuUserRecord, u)
  35. CpuTotalRecord = append(CpuTotalRecord, u)
  36. NetRecvRecord = append(NetRecvRecord, u)
  37. NetSentRecord = append(NetSentRecord, u)
  38. DiskWriteRecord = append(DiskWriteRecord, u)
  39. DiskReadRecord = append(DiskReadRecord, u)
  40. }
  41. }
  42. func RecordServerAnalytic() {
  43. logger.Info("RecordServerAnalytic Started")
  44. for {
  45. now := time.Now()
  46. recordCpu(now) // this func will spend more than 1 second.
  47. recordNetwork(now)
  48. recordDiskIO(now)
  49. }
  50. }