mock_topo.go 14 KB

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