stats_manager.go 2.3 KB

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