stats_manager.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 = "kuiper_source_"
  33. case "op":
  34. prefix = "kuiper_op_"
  35. case "sink":
  36. prefix = "kuiper_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. result[sm.prefix+sm.opId+"_"+strconv.Itoa(sm.instanceId)+"_"+LastInvocation] = sm.lastInvocation.String()
  74. result[sm.prefix+sm.opId+"_"+strconv.Itoa(sm.instanceId)+"_"+ProcessLatencyMs] = sm.processLatency
  75. return result
  76. }