stats_manager.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package nodes
  2. import (
  3. "fmt"
  4. "github.com/emqx/kuiper/xstream/api"
  5. "time"
  6. )
  7. //The statManager is not thread safe. Make sure it is used in only one instance
  8. type StatManager struct {
  9. //metrics
  10. totalRecordsIn int64
  11. totalRecordsOut int64
  12. totalExceptions int64
  13. processLatency int64
  14. lastInvocation time.Time
  15. bufferLength int64
  16. //configs
  17. opType string //"source", "op", "sink"
  18. prefix string
  19. processTimeStart time.Time
  20. opId string
  21. instanceId int
  22. }
  23. const RecordsInTotal = "records_in_total"
  24. const RecordsOutTotal = "records_out_total"
  25. const ExceptionsTotal = "exceptions_total"
  26. const ProcessLatencyMs = "process_latency_ms"
  27. const LastInvocation = "last_invocation"
  28. const BufferLength = "buffer_length"
  29. var MetricNames = []string{RecordsInTotal, RecordsOutTotal, ExceptionsTotal, ProcessLatencyMs, BufferLength, LastInvocation}
  30. func NewStatManager(opType string, ctx api.StreamContext) (*StatManager, error) {
  31. var prefix string
  32. switch opType {
  33. case "source":
  34. prefix = "source_"
  35. case "op":
  36. prefix = "op_"
  37. case "sink":
  38. prefix = "sink_"
  39. default:
  40. return nil, fmt.Errorf("invalid opType %s, must be \"source\", \"sink\" or \"op\"", opType)
  41. }
  42. sm := &StatManager{
  43. opType: opType,
  44. prefix: prefix,
  45. opId: ctx.GetOpId(),
  46. instanceId: ctx.GetInstanceId(),
  47. }
  48. return sm, nil
  49. }
  50. func (sm *StatManager) IncTotalRecordsIn() {
  51. sm.totalRecordsIn++
  52. }
  53. func (sm *StatManager) IncTotalRecordsOut() {
  54. sm.totalRecordsOut++
  55. }
  56. func (sm *StatManager) IncTotalExceptions() {
  57. sm.totalExceptions++
  58. var t time.Time
  59. sm.processTimeStart = t
  60. }
  61. func (sm *StatManager) ProcessTimeStart() {
  62. sm.lastInvocation = time.Now()
  63. sm.processTimeStart = sm.lastInvocation
  64. }
  65. func (sm *StatManager) ProcessTimeEnd() {
  66. if !sm.processTimeStart.IsZero() {
  67. sm.processLatency = int64(time.Since(sm.processTimeStart) / time.Millisecond)
  68. }
  69. }
  70. func (sm *StatManager) SetBufferLength(l int64) {
  71. sm.bufferLength = l
  72. }
  73. func (sm *StatManager) GetMetrics() []interface{} {
  74. result := []interface{}{
  75. sm.totalRecordsIn, sm.totalRecordsOut, sm.totalExceptions, sm.processLatency, sm.bufferLength,
  76. }
  77. if !sm.lastInvocation.IsZero(){
  78. result = append(result, sm.lastInvocation.Format("2006-01-02T15:04:05.999999"))
  79. }
  80. return result
  81. }