mock_topo.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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 topotest
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. "github.com/lf-edge/ekuiper/internal/conf"
  19. "github.com/lf-edge/ekuiper/internal/processor"
  20. "github.com/lf-edge/ekuiper/internal/testx"
  21. "github.com/lf-edge/ekuiper/internal/topo"
  22. "github.com/lf-edge/ekuiper/internal/topo/node"
  23. "github.com/lf-edge/ekuiper/internal/topo/planner"
  24. "github.com/lf-edge/ekuiper/internal/topo/topotest/mockclock"
  25. "github.com/lf-edge/ekuiper/internal/topo/topotest/mocknode"
  26. "github.com/lf-edge/ekuiper/internal/xsql"
  27. "github.com/lf-edge/ekuiper/pkg/api"
  28. "github.com/lf-edge/ekuiper/pkg/ast"
  29. "github.com/lf-edge/ekuiper/pkg/cast"
  30. "reflect"
  31. "strings"
  32. "testing"
  33. "time"
  34. )
  35. func init() {
  36. testx.InitEnv()
  37. }
  38. const POSTLEAP = 1000 // Time change after all data sends out
  39. type RuleTest struct {
  40. Name string
  41. Sql string
  42. R interface{} // The result
  43. M map[string]interface{} // final metrics
  44. T *topo.PrintableTopo // printable topo, an optional field
  45. W int // wait time for each data sending, in milli
  46. }
  47. func CompareMetrics(tp *topo.Topo, m map[string]interface{}) (err error) {
  48. keys, values := tp.GetMetrics()
  49. for k, v := range m {
  50. var (
  51. index int
  52. key string
  53. matched bool
  54. )
  55. for index, key = range keys {
  56. if k == key {
  57. if strings.HasSuffix(k, "process_latency_us") {
  58. if values[index].(int64) >= v.(int64) {
  59. matched = true
  60. continue
  61. } else {
  62. break
  63. }
  64. }
  65. if values[index] == v {
  66. matched = true
  67. }
  68. break
  69. }
  70. }
  71. if matched {
  72. continue
  73. }
  74. if conf.Config.Basic.Debug == true {
  75. for i, k := range keys {
  76. conf.Log.Printf("%s:%v", k, values[i])
  77. }
  78. }
  79. //do not find
  80. if index < len(values) {
  81. return fmt.Errorf("metrics mismatch for %s:\n\nexp=%#v(%T)\n\ngot=%#v(%T)\n\n", k, v, v, values[index], values[index])
  82. } else {
  83. return fmt.Errorf("metrics mismatch for %s:\n\nexp=%#v\n\ngot=nil\n\n", k, v)
  84. }
  85. }
  86. return nil
  87. }
  88. func CommonResultFunc(result [][]byte) interface{} {
  89. var maps [][]map[string]interface{}
  90. for _, v := range result {
  91. var mapRes []map[string]interface{}
  92. err := json.Unmarshal(v, &mapRes)
  93. if err != nil {
  94. panic(fmt.Sprintf("Failed to parse the input %v into map", string(v)))
  95. }
  96. maps = append(maps, mapRes)
  97. }
  98. return maps
  99. }
  100. func DoRuleTest(t *testing.T, tests []RuleTest, j int, opt *api.RuleOption, wait int) {
  101. doRuleTestBySinkProps(t, tests, j, opt, wait, nil, CommonResultFunc)
  102. }
  103. func doRuleTestBySinkProps(t *testing.T, tests []RuleTest, j int, opt *api.RuleOption, w int, sinkProps map[string]interface{}, resultFunc func(result [][]byte) interface{}) {
  104. fmt.Printf("The test bucket for option %d size is %d.\n\n", j, len(tests))
  105. for i, tt := range tests {
  106. datas, dataLength, tp, mockSink, errCh := createStream(t, tt, j, opt, sinkProps)
  107. if tp == nil {
  108. t.Errorf("topo is not created successfully")
  109. break
  110. }
  111. wait := tt.W
  112. if wait == 0 {
  113. if w > 0 {
  114. wait = w
  115. } else {
  116. wait = 5
  117. }
  118. }
  119. switch opt.Qos {
  120. case api.ExactlyOnce:
  121. wait *= 10
  122. case api.AtLeastOnce:
  123. wait *= 3
  124. }
  125. var retry int
  126. if opt.Qos > api.AtMostOnce {
  127. for retry = 3; retry > 0; retry-- {
  128. if tp.GetCoordinator() == nil || !tp.GetCoordinator().IsActivated() {
  129. conf.Log.Debugf("waiting for coordinator ready %d\n", retry)
  130. time.Sleep(10 * time.Millisecond)
  131. } else {
  132. break
  133. }
  134. }
  135. if retry < 0 {
  136. t.Error("coordinator timeout")
  137. t.FailNow()
  138. }
  139. }
  140. if err := sendData(t, dataLength, tt.M, datas, errCh, tp, POSTLEAP, wait); err != nil {
  141. t.Errorf("send data error %s", err)
  142. break
  143. }
  144. compareResult(t, mockSink, resultFunc, tt, i, tp)
  145. }
  146. }
  147. func compareResult(t *testing.T, mockSink *mocknode.MockSink, resultFunc func(result [][]byte) interface{}, tt RuleTest, i int, tp *topo.Topo) {
  148. // Check results
  149. results := mockSink.GetResults()
  150. maps := resultFunc(results)
  151. if !reflect.DeepEqual(tt.R, maps) {
  152. t.Errorf("%d. %q\n\nresult mismatch:\n\nexp=%#v\n\ngot=%#v\n\n", i, tt.Sql, tt.R, maps)
  153. }
  154. if err := CompareMetrics(tp, tt.M); err != nil {
  155. t.Errorf("%d. %q\n\nmetrics mismatch:\n\n%s\n\n", i, tt.Sql, err)
  156. }
  157. if tt.T != nil {
  158. topo := tp.GetTopo()
  159. if !reflect.DeepEqual(tt.T, topo) {
  160. t.Errorf("%d. %q\n\ntopo mismatch:\n\nexp=%#v\n\ngot=%#v\n\n", i, tt.Sql, tt.T, topo)
  161. }
  162. }
  163. tp.Cancel()
  164. }
  165. func sendData(t *testing.T, dataLength int, metrics map[string]interface{}, datas [][]*xsql.Tuple, errCh <-chan error, tp *topo.Topo, postleap int, wait int) error {
  166. // Send data and move time
  167. mockClock := mockclock.GetMockClock()
  168. // Set the current time
  169. mockClock.Add(0)
  170. // TODO assume multiple data source send the data in order and has the same length
  171. for i := 0; i < dataLength; i++ {
  172. for _, d := range datas {
  173. time.Sleep(time.Duration(wait) * time.Millisecond)
  174. // Make sure time is going forward only
  175. // gradually add up time to ensure checkpoint is triggered before the data send
  176. for n := conf.GetNowInMilli() + 100; d[i].Timestamp+100 > n; n += 100 {
  177. if d[i].Timestamp < n {
  178. n = d[i].Timestamp
  179. }
  180. mockClock.Set(cast.TimeFromUnixMilli(n))
  181. conf.Log.Debugf("Clock set to %d", conf.GetNowInMilli())
  182. time.Sleep(1)
  183. }
  184. select {
  185. case err := <-errCh:
  186. t.Log(err)
  187. tp.Cancel()
  188. return err
  189. default:
  190. }
  191. }
  192. }
  193. mockClock.Add(time.Duration(postleap) * time.Millisecond)
  194. conf.Log.Debugf("Clock add to %d", conf.GetNowInMilli())
  195. // Check if stream done. Poll for metrics,
  196. time.Sleep(10 * time.Millisecond)
  197. var retry int
  198. for retry = 4; retry > 0; retry-- {
  199. if err := CompareMetrics(tp, metrics); err == nil {
  200. break
  201. } else {
  202. conf.Log.Errorf("check metrics error at %d: %s", retry, err)
  203. }
  204. time.Sleep(1000 * time.Millisecond)
  205. }
  206. if retry == 0 {
  207. t.Error("send data timeout")
  208. } else if retry < 2 {
  209. conf.Log.Debugf("try %d for metric comparison\n", 2-retry)
  210. }
  211. return nil
  212. }
  213. func createStream(t *testing.T, tt RuleTest, j int, opt *api.RuleOption, sinkProps map[string]interface{}) ([][]*xsql.Tuple, int, *topo.Topo, *mocknode.MockSink, <-chan error) {
  214. mockclock.ResetClock(1541152486000)
  215. // Create stream
  216. var (
  217. sources []*node.SourceNode
  218. datas [][]*xsql.Tuple
  219. dataLength int
  220. )
  221. parser := xsql.NewParser(strings.NewReader(tt.Sql))
  222. if stmt, err := xsql.Language.Parse(parser); err != nil {
  223. t.Errorf("parse sql %s error: %s", tt.Sql, err)
  224. } else {
  225. if selectStmt, ok := stmt.(*ast.SelectStatement); !ok {
  226. t.Errorf("sql %s is not a select statement", tt.Sql)
  227. } else {
  228. streams := xsql.GetStreams(selectStmt)
  229. for _, stream := range streams {
  230. data, ok := mocknode.TestData[stream]
  231. if !ok {
  232. continue
  233. }
  234. dataLength = len(data)
  235. datas = append(datas, data)
  236. }
  237. }
  238. }
  239. mockSink := mocknode.NewMockSink()
  240. sink := node.NewSinkNodeWithSink("mockSink", mockSink, sinkProps)
  241. tp, err := planner.PlanWithSourcesAndSinks(&api.Rule{Id: fmt.Sprintf("%s_%d", tt.Name, j), Sql: tt.Sql, Options: opt}, sources, []*node.SinkNode{sink})
  242. if err != nil {
  243. t.Error(err)
  244. return nil, 0, nil, nil, nil
  245. }
  246. errCh := tp.Open()
  247. return datas, dataLength, tp, mockSink, errCh
  248. }
  249. // Create or drop streams
  250. func HandleStream(createOrDrop bool, names []string, t *testing.T) {
  251. p := processor.NewStreamProcessor()
  252. for _, name := range names {
  253. var sql string
  254. if createOrDrop {
  255. switch name {
  256. case "demo":
  257. sql = `CREATE STREAM demo (
  258. color STRING,
  259. size BIGINT,
  260. ts BIGINT
  261. ) WITH (DATASOURCE="demo", TYPE="mock", FORMAT="json", KEY="ts");`
  262. case "demoError":
  263. sql = `CREATE STREAM demoError (
  264. color STRING,
  265. size BIGINT,
  266. ts BIGINT
  267. ) WITH (DATASOURCE="demoError", TYPE="mock", FORMAT="json", KEY="ts");`
  268. case "demo1":
  269. sql = `CREATE STREAM demo1 (
  270. temp FLOAT,
  271. hum BIGINT,` +
  272. "`from`" + ` STRING,
  273. ts BIGINT
  274. ) WITH (DATASOURCE="demo1", TYPE="mock", FORMAT="json", KEY="ts");`
  275. case "demoTable":
  276. sql = `CREATE TABLE demoTable (
  277. device STRING,
  278. ts BIGINT
  279. ) WITH (DATASOURCE="demoTable", TYPE="mock", RETAIN_SIZE="3");`
  280. case "sessionDemo":
  281. sql = `CREATE STREAM sessionDemo (
  282. temp FLOAT,
  283. hum BIGINT,
  284. ts BIGINT
  285. ) WITH (DATASOURCE="sessionDemo", TYPE="mock", FORMAT="json", KEY="ts");`
  286. case "demoE":
  287. sql = `CREATE STREAM demoE (
  288. color STRING,
  289. size BIGINT,
  290. ts BIGINT
  291. ) WITH (DATASOURCE="demoE", TYPE="mock", FORMAT="json", KEY="ts", TIMESTAMP="ts");`
  292. case "demo1E":
  293. sql = `CREATE STREAM demo1E (
  294. temp FLOAT,
  295. hum BIGINT,
  296. ts BIGINT
  297. ) WITH (DATASOURCE="demo1E", TYPE="mock", FORMAT="json", KEY="ts", TIMESTAMP="ts");`
  298. case "sessionDemoE":
  299. sql = `CREATE STREAM sessionDemoE (
  300. temp FLOAT,
  301. hum BIGINT,
  302. ts BIGINT
  303. ) WITH (DATASOURCE="sessionDemoE", TYPE="mock", FORMAT="json", KEY="ts", TIMESTAMP="ts");`
  304. case "demoErr":
  305. sql = `CREATE STREAM demoErr (
  306. color STRING,
  307. size BIGINT,
  308. ts BIGINT
  309. ) WITH (DATASOURCE="demoErr", TYPE="mock", FORMAT="json", KEY="ts", TIMESTAMP="ts");`
  310. case "ldemo":
  311. sql = `CREATE STREAM ldemo (
  312. ) WITH (DATASOURCE="ldemo", TYPE="mock", FORMAT="json");`
  313. case "ldemo1":
  314. sql = `CREATE STREAM ldemo1 (
  315. ) WITH (DATASOURCE="ldemo1", TYPE="mock", FORMAT="json");`
  316. case "lsessionDemo":
  317. sql = `CREATE STREAM lsessionDemo (
  318. ) WITH (DATASOURCE="lsessionDemo", TYPE="mock", FORMAT="json");`
  319. case "ext":
  320. sql = "CREATE STREAM ext (count bigint) WITH (DATASOURCE=\"ext\", FORMAT=\"JSON\", TYPE=\"random\", CONF_KEY=\"ext\")"
  321. case "ext2":
  322. sql = "CREATE STREAM ext2 (count bigint) WITH (DATASOURCE=\"ext2\", FORMAT=\"JSON\", TYPE=\"random\", CONF_KEY=\"dedup\")"
  323. case "extpy":
  324. sql = "CREATE STREAM extpy (name string, value bigint) WITH (FORMAT=\"JSON\", TYPE=\"pyjson\", CONF_KEY=\"ext\")"
  325. case "text":
  326. sql = "CREATE STREAM text (slogan string, brand string) WITH (DATASOURCE=\"text\", TYPE=\"mock\", FORMAT=\"JSON\")"
  327. case "binDemo":
  328. sql = "CREATE STREAM binDemo () WITH (DATASOURCE=\"binDemo\", TYPE=\"mock\", FORMAT=\"BINARY\")"
  329. case "table1":
  330. sql = `CREATE TABLE table1 (
  331. name STRING,
  332. size BIGINT,
  333. id BIGINT
  334. ) WITH (DATASOURCE="lookup.json", FORMAT="json", CONF_KEY="test");`
  335. case "helloStr":
  336. sql = `CREATE STREAM helloStr (name string) WITH (DATASOURCE="helloStr", TYPE="mock", FORMAT="JSON")`
  337. case "commands":
  338. sql = `CREATE STREAM commands (cmd string, base64_img string, encoded_json string) WITH (DATASOURCE="commands", FORMAT="JSON", TYPE="mock")`
  339. case "fakeBin":
  340. sql = "CREATE STREAM fakeBin () WITH (DATASOURCE=\"fakeBin\", TYPE=\"mock\", FORMAT=\"BINARY\")"
  341. case "shelves":
  342. sql = `CREATE STREAM shelves (
  343. name string,
  344. size BIGINT,
  345. shelf STRUCT(theme STRING,id BIGINT, subfield STRING)
  346. ) WITH (DATASOURCE="shelves", TYPE="mock", FORMAT="json");`
  347. case "mes":
  348. sql = `CREATE STREAM mes (message_id string, text string) WITH (DATASOURCE="mes", TYPE="mock", FORMAT="JSON")`
  349. default:
  350. t.Errorf("create stream %s fail", name)
  351. }
  352. } else {
  353. if strings.Index(name, "table") == 0 {
  354. sql = `DROP TABLE ` + name
  355. } else {
  356. sql = `DROP STREAM ` + name
  357. }
  358. }
  359. _, err := p.ExecStmt(sql)
  360. if err != nil {
  361. t.Log(err)
  362. }
  363. }
  364. }
  365. type RuleCheckpointTest struct {
  366. RuleTest
  367. PauseSize int // Stop stream after sending pauseSize source to test checkpoint resume
  368. Cc int // checkpoint count when paused
  369. PauseMetric map[string]interface{} // The metric to check when paused
  370. }
  371. func DoCheckpointRuleTest(t *testing.T, tests []RuleCheckpointTest, j int, opt *api.RuleOption) {
  372. fmt.Printf("The test bucket for option %d size is %d.\n\n", j, len(tests))
  373. for i, tt := range tests {
  374. datas, dataLength, tp, mockSink, errCh := createStream(t, tt.RuleTest, j, opt, nil)
  375. if tp == nil {
  376. t.Errorf("topo is not created successfully")
  377. break
  378. }
  379. var retry int
  380. for retry = 10; retry > 0; retry-- {
  381. if tp.GetCoordinator() == nil || !tp.GetCoordinator().IsActivated() {
  382. conf.Log.Debugf("waiting for coordinator ready %d\n", retry)
  383. time.Sleep(10 * time.Millisecond)
  384. } else {
  385. break
  386. }
  387. }
  388. if retry == 0 {
  389. t.Error("coordinator timeout")
  390. t.FailNow()
  391. }
  392. conf.Log.Debugf("Start sending first phase data done at %d", conf.GetNowInMilli())
  393. if err := sendData(t, tt.PauseSize, tt.PauseMetric, datas, errCh, tp, 100, 100); err != nil {
  394. t.Errorf("first phase send data error %s", err)
  395. break
  396. }
  397. conf.Log.Debugf("Send first phase data done at %d", conf.GetNowInMilli())
  398. // compare checkpoint count
  399. time.Sleep(10 * time.Millisecond)
  400. for retry = 3; retry > 0; retry-- {
  401. actual := tp.GetCoordinator().GetCompleteCount()
  402. if tt.Cc == actual {
  403. break
  404. } else {
  405. conf.Log.Debugf("check checkpointCount error at %d: %d\n", retry, actual)
  406. }
  407. time.Sleep(200 * time.Millisecond)
  408. }
  409. cc := tp.GetCoordinator().GetCompleteCount()
  410. tp.Cancel()
  411. if retry == 0 {
  412. t.Errorf("%d-%d. checkpoint count\n\nresult mismatch:\n\nexp=%#v\n\ngot=%d\n\n", i, j, tt.Cc, cc)
  413. return
  414. } else if retry < 3 {
  415. conf.Log.Debugf("try %d for checkpoint count\n", 4-retry)
  416. }
  417. tp.Cancel()
  418. time.Sleep(10 * time.Millisecond)
  419. // resume stream
  420. conf.Log.Debugf("Resume stream at %d", conf.GetNowInMilli())
  421. errCh = tp.Open()
  422. conf.Log.Debugf("After open stream at %d", conf.GetNowInMilli())
  423. if err := sendData(t, dataLength, tt.M, datas, errCh, tp, POSTLEAP, 10); err != nil {
  424. t.Errorf("second phase send data error %s", err)
  425. break
  426. }
  427. compareResult(t, mockSink, CommonResultFunc, tt.RuleTest, i, tp)
  428. }
  429. }
  430. func CreateRule(name, sql string) (*api.Rule, error) {
  431. p := processor.NewRuleProcessor()
  432. p.ExecDrop(name)
  433. return p.ExecCreate(name, sql)
  434. }