random_source.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. // Copyright 2021 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package main
  15. import (
  16. "bytes"
  17. "encoding/json"
  18. "fmt"
  19. "github.com/lf-edge/ekuiper/sdk/go/api"
  20. "github.com/mitchellh/mapstructure"
  21. "math/rand"
  22. "strings"
  23. "time"
  24. )
  25. const dedupStateKey = "input"
  26. type randomSourceConfig struct {
  27. Interval int `json:"interval"`
  28. Seed int `json:"seed"`
  29. Pattern map[string]interface{} `json:"pattern"`
  30. // how long will the source trace for deduplication. If 0, deduplicate is disabled; if negative, deduplicate will be the whole life time
  31. Deduplicate int `json:"deduplicate"`
  32. Format string `json:"format"`
  33. }
  34. // Emit data randomly with only a string field
  35. type randomSource struct {
  36. conf *randomSourceConfig
  37. list [][]byte
  38. }
  39. func (s *randomSource) Configure(_ string, props map[string]interface{}) error {
  40. cfg := &randomSourceConfig{
  41. Format: "json",
  42. }
  43. err := mapstructure.Decode(props, cfg)
  44. if err != nil {
  45. return fmt.Errorf("read properties %v fail with error: %v", props, err)
  46. }
  47. if cfg.Interval <= 0 {
  48. return fmt.Errorf("source `random` property `interval` must be a positive integer but got %d", cfg.Interval)
  49. }
  50. if cfg.Pattern == nil {
  51. return fmt.Errorf("source `random` property `pattern` is required")
  52. }
  53. if cfg.Seed <= 0 {
  54. return fmt.Errorf("source `random` property `seed` must be a positive integer but got %d", cfg.Seed)
  55. }
  56. if !strings.EqualFold(cfg.Format, "json") {
  57. return fmt.Errorf("random source only supports `json` format")
  58. }
  59. s.conf = cfg
  60. return nil
  61. }
  62. func (s *randomSource) Open(ctx api.StreamContext, consumer chan<- api.SourceTuple, _ chan<- error) {
  63. logger := ctx.GetLogger()
  64. logger.Infof("open random source with config %+v", s.conf)
  65. if s.conf.Deduplicate != 0 {
  66. var list interface{}
  67. // dedup not supported yet
  68. //list, err := ctx.GetState(dedupStateKey)
  69. //if err != nil {
  70. // errCh <- err
  71. // return
  72. //}
  73. if list == nil {
  74. list = make([][]byte, 0)
  75. } else {
  76. if l, ok := list.([][]byte); ok {
  77. logger.Debugf("restore list %v", l)
  78. s.list = l
  79. } else {
  80. s.list = make([][]byte, 0)
  81. logger.Warnf("random source gets invalid state, ignore it")
  82. }
  83. }
  84. }
  85. t := time.NewTicker(time.Duration(s.conf.Interval) * time.Millisecond)
  86. defer t.Stop()
  87. for {
  88. select {
  89. case <-t.C:
  90. next := randomize(s.conf.Pattern, s.conf.Seed)
  91. if s.conf.Deduplicate != 0 && s.isDup(ctx, next) {
  92. logger.Debugf("find duplicate")
  93. continue
  94. }
  95. logger.Debugf("Send out data %v", next)
  96. consumer <- api.NewDefaultSourceTuple(next, nil)
  97. case <-ctx.Done():
  98. return
  99. }
  100. }
  101. }
  102. func randomize(p map[string]interface{}, seed int) map[string]interface{} {
  103. r := make(map[string]interface{})
  104. for k, v := range p {
  105. //TODO other data types
  106. vf, ok := v.(float64)
  107. if !ok {
  108. break
  109. }
  110. vi := int(vf)
  111. r[k] = vi + rand.Intn(seed)
  112. }
  113. return r
  114. }
  115. func (s *randomSource) isDup(ctx api.StreamContext, next map[string]interface{}) bool {
  116. logger := ctx.GetLogger()
  117. ns, err := json.Marshal(next)
  118. if err != nil {
  119. logger.Warnf("invalid input data %v", next)
  120. return true
  121. }
  122. for _, ps := range s.list {
  123. if bytes.Compare(ns, ps) == 0 {
  124. logger.Debugf("got duplicate %s", ns)
  125. return true
  126. }
  127. }
  128. logger.Debugf("no duplicate %s", ns)
  129. if s.conf.Deduplicate > 0 && len(s.list) >= s.conf.Deduplicate {
  130. s.list = s.list[1:]
  131. }
  132. s.list = append(s.list, ns)
  133. // State not supported yet
  134. // ctx.PutState(dedupStateKey, s.list)
  135. return false
  136. }
  137. func (s *randomSource) Close(_ api.StreamContext) error {
  138. return nil
  139. }