mql_run.go 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374
  1. package odbcmql
  2. import (
  3. "bufio"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "log"
  8. "math/rand"
  9. "os"
  10. "path/filepath"
  11. "regexp"
  12. "runtime"
  13. "strconv"
  14. "strings"
  15. "sync"
  16. "sync/atomic"
  17. "testing"
  18. "time"
  19. odb "git.wecise.com/wecise/odb-go/odb"
  20. "git.wecise.com/wecise/odb-go/odb/mql/qstru"
  21. "gitee.com/wecisecode/util/cast"
  22. mcfg "gitee.com/wecisecode/util/cfg"
  23. "gitee.com/wecisecode/util/filewalker"
  24. "gitee.com/wecisecode/util/pqc"
  25. "gitee.com/wecisecode/util/set/strset"
  26. "gitee.com/wecisecode/util/spliter"
  27. "github.com/gofrs/flock"
  28. "github.com/stretchr/testify/assert"
  29. )
  30. var ODBC odb.Client
  31. var ODBError error
  32. var debug bool
  33. // var checkCassSchema bool
  34. var default_keyspace = `oktest`
  35. var default_odbpaths = `127.0.0.1:11001`
  36. var ksnative = default_keyspace + "_native"
  37. func init() {
  38. logprefix := config.GetString("log.prefix", "")
  39. if logprefix != "" {
  40. logprefix += " "
  41. }
  42. logger.SetFormat(logprefix+"yyyy-MM-dd HH:mm:ss.SSSSSS [pid] [level] msg", "\n")
  43. odbpaths := strset.New(strings.Split(mcfg.CommandArgs.GetString("odb",
  44. strings.Join(mcfg.Environs.GetStrings("ODBPATH",
  45. config.GetStrings("odbc.odbpath", default_odbpaths)...), ",")), ",")...).List()
  46. keyspace := mcfg.CommandArgs.GetString("keyspace",
  47. mcfg.Environs.GetString("KEYSPACE", config.GetString("odbc.keyspace", default_keyspace)))
  48. cassdc := mcfg.CommandArgs.GetString("cassandra.dc",
  49. mcfg.Environs.GetString("CASSANDRADC", config.GetString("cassandra.dc", "")))
  50. if cassdc == "" || cassdc == "dc1" {
  51. ksnative = keyspace + "_native"
  52. } else {
  53. ksnative = keyspace + "_" + cassdc + "_native"
  54. }
  55. ksnative = mcfg.CommandArgs.GetString("ksnative",
  56. mcfg.Environs.GetString("KSNATIVE", config.GetString("odbc.ksnative", ksnative)))
  57. debug = mcfg.CommandArgs.GetBool("debug", false)
  58. // checkCassSchema = mcfg.CommandArgs.GetBool("ccs", true)
  59. ODBC, ODBError = odb.NewClient(&odb.Config{
  60. Keyspace: keyspace,
  61. Hosts: odbpaths,
  62. Debug: debug,
  63. })
  64. }
  65. func Run(t *testing.T) {
  66. if mcfg.CommandArgs.GetString("keyspace?") == "keyspace?" {
  67. if ODBC != nil {
  68. fmt.Println(ODBC.Config().Keyspace)
  69. os.Exit(0)
  70. }
  71. os.Exit(0)
  72. }
  73. if mcfg.CommandArgs.GetString("odbpath?") == "odbpath?" {
  74. if ODBC != nil {
  75. fmt.Println(ODBC.Config().Hosts)
  76. os.Exit(0)
  77. }
  78. os.Exit(0)
  79. }
  80. if mcfg.CommandArgs.GetString("odbver?") == "odbver?" {
  81. if ODBC != nil {
  82. fmt.Println(ODBC.Versline())
  83. os.Exit(0)
  84. }
  85. os.Exit(0)
  86. }
  87. spath := strings.Split(config.GetString("test.mql.path"), " ")
  88. if len(os.Args) > 1 {
  89. if len(os.Args) > 2 && os.Args[1] == "-" {
  90. s := strings.Join(os.Args[2:], " ")
  91. spath = []string{"/tmp/1.mql"}
  92. os.WriteFile(spath[0], []byte(s+"/**output()**/"), os.ModePerm)
  93. } else {
  94. for i := 1; i < len(os.Args); i++ {
  95. ap := os.Args[i]
  96. if strings.HasPrefix(ap, "-test.") {
  97. break
  98. }
  99. if strings.Contains(ap, "=") {
  100. continue
  101. }
  102. if (ap == "-" || ap == "--") && i+1 < len(os.Args) {
  103. s := strings.Join(os.Args[i+1:], " ")
  104. spath = []string{"/tmp/1.mql"}
  105. os.WriteFile(spath[0], []byte(s+"\n/**output()**/"), os.ModePerm)
  106. break
  107. }
  108. spath = append(spath, ap)
  109. }
  110. }
  111. }
  112. if len(spath) == 0 || len(spath) == 1 && len(spath[0]) == 0 {
  113. fmt.Print(`循环遍历执行指定路径下的 mql 文件
  114. usage: mql path [options] -- mqlstatement
  115. path 指定mql文件所在路径,通配符 ** 表示任意字符,* 表示除分隔符以外的任意字符, . 表示递归当前目录下的所有子目录
  116. 为避免 shell 自动将 * 转换为文件名列表,可以将指定的 path 用引号包含
  117. mqlstatement 指定要执行的 mql 语句,支持多条语句,语句之间用分号 ; 分隔
  118. options:
  119. match=^\\d+.* 文件名匹配正则表达式,默认为所有以数字开头命名的文件
  120. odb=` + default_odbpaths + ` 指定odbserver路径,默认通过环境变量ODBPATH或通过ETCD相关配置获取
  121. keyspace=` + default_keyspace + ` 指定keyspace,默认通过环境变量KEYSPACE获取
  122. ksnative=` + default_keyspace + `_native 指定native keyspace,默认通过环境变量KSNATIVE获取
  123. debug=true 开启调试模式,输出更多信息
  124. 环境变量需求:
  125. KEYSPACE=` + default_keyspace + `
  126. KSNATIVE=` + default_keyspace + `_native
  127. ODBPATH=` + default_odbpaths + `
  128. ETCDPATH=127.0.0.1:2379
  129. ETCDUSER=
  130. ETCDPASS=
  131. CASSANDRAPATH=127.0.0.1
  132. CASSANDRALOOKUP=false
  133. NATSPATH=nats://user:N5JbKeT1C3uOUh317OVXjg==@127.0.0.1:4222
  134. LANG=zh_CN.utf8
  135. LC_ALL=zh_CN.utf8
  136. 可通过mql.conf配置运行参数:
  137. [odbc]
  138. ;指定odbserver路径
  139. odbpath=` + default_odbpaths + `
  140. ;指定keyspace
  141. keyspace=` + default_keyspace + `
  142. ;指定native keyspace
  143. ksnative=` + default_keyspace + `_native
  144. mql语句扩展说明:
  145. mql语句中的内容替换:
  146. 随机字符替换:
  147. mql语句中的 '...N Bytes...' 会被替换为 N 个随机可见字符,N 为自然数
  148. 变量替换:
  149. mql语句中 '{%<f>,<varname>}' 形式的内容会被替换为,以 %<f> 作为格式化标记的 <varname> 变量的内容
  150. 目前支持的 <varname> 包括:
  151. keyspace 当前指定的 Keyspace
  152. ksnative Native Keyspace
  153. mqli 当前mql语句的循环值,参考 loop(N)
  154. filei 当前文件的循环值,参考 scope(file) loop(N)
  155. diri 当前目录的循环值,参考 scope(dir) loop(N)
  156. topi 整个执行进程的循环值,参考 scope(top) loop(N)
  157. mqlcount 当前mql语句的总计数
  158. filecount 当前文件的总计数
  159. dircount 当前目录的总计数
  160. topcount 整个执行进程的总计数
  161. mql语句中第一个 /** 到 最后一个 **/ 之间的内容可以标注执行若干预定义动作,多个动作标注用空格分隔
  162. 如 /** output() sleep(1) **/ 表示忽略当前语句执行过程中的任何报错,执行完成后等待一秒后再继续执行下一语句
  163. 目前支持的预定义动作如下:
  164. skip() 跳过当前语句,以及其它的所有预定义动作
  165. 可用于暂时屏蔽一条语句的执行
  166. params(V) 用于提供 prepare 语句中 ? 的对应值,V 为 JSON 格式编码的数组
  167. 对应值中不能有包含逗号和右括号,如果需要逗号用 \u002c 代替,右括号用 \u0029 代替
  168. subscribe(S) 订阅指定主题的消息通知 S,输出收到的通知信息,S 为要订阅主题的的名称字符串,同一主题只会被订阅一次
  169. unsubscribe(S) 取消订阅指定主题的消息通知 S,S 为要订阅主题的名称字符串
  170. fork(G) 新建并行线程分支,执行当前语句的同时,继续执行后续语句,G 为线程组名,配合 wait 使用
  171. wait(G) 执行当前语句前,等待之前创建的分支结束,G 为线程组名,对应由 fork 创建的所有同名线程分支,G 为空表示所有
  172. beforerun(F,...) 执行当前语句前,执行一系列预定义函数,以通过一些简单逻辑处理产生模拟数据,目前支持的函数包括
  173. set(S,V) 设置变量,S 为变量名,V为变量值
  174. add(S,V,u) 累加变量,S 为变量名,V为增量值,u为可选的变量单位,如时间段单位 second,minute,hour
  175. mod(S,V) 变量取模,相当于 S = S % V
  176. case(C,F) 根据条件 C 执行函数 F
  177. ------------- 针对错误处理的相关动作
  178. retry(N) 出错重试 N 次,N为自然数,默认为 0,
  179. onerror(O,E,...) retry后仍然有错时的处理方法,E为特定的错误信息关键字,不指定则为任意错误,O为处理方法,包括:
  180. break 中断当前语句的循环,继续顺序执行其它语句,没有循环时与pass无区别
  181. continue 忽略报错,继续执行,在循环中时,继续下一轮循环
  182. must 报错才正常,否则中断执行,报告期待错误信息不符,退出当前进程
  183. exit 停止执行,退出当前进程,此为默认处理方式
  184. noerrinfo() 存在 retry 或 onerror 处理时,不输出错误信息
  185. ------------- 以上的预定义动作只对当前语句起作用,下面的预定义动作可以指定其作用范围
  186. scope(S) 相关动作的作用范围 S 包括 top,dir,file,mql,默认作用范围为 mql 当前语句
  187. 如:scope(file) parallel(3) loop(5) 并发循环执行本文件五次,最大并行数限制为3
  188. qmeta(O) mql执行时设置特定的选项,O为json对象
  189. timeout(D) mql执行超时设置,D 为时间段,默认为一分钟
  190. 时间段 D 支持单位 d(天),h(时),m(分),s(秒),ms(毫秒),us(微秒),ns(纳秒),默认为毫秒
  191. loop(N) 循环执行 N 次,N 为正整数,默认执行一次
  192. 执行前会替换 mql 语句及 params 参数中的循环次数标记
  193. loopfrom(N) 设置循环执行计数起始值 N,默认为 1,该值仅影响替换 mql 语句及 params 参数中的循环次数标记
  194. loopstep(N) 设置循环执行计数步长值 N,默认为 1,该值仅影响替换 mql 语句及 params 参数中的循环次数标记
  195. parallel(N) 并发执行,N 为最大并行数,不指定 N 表示不限制并行数
  196. set(S,V) 设置变量,S 为变量名,V为变量值
  197. ------------- 以上为执行语句前的预定义动作,下面是执行完成后的预定义动作
  198. sleep(D) 执行完成后等待时间段 D 后再继续执行下一语句
  199. output() 输出执行结果
  200. outputcount() 输出执行结果记录条数
  201. metainfo() 输出执行结果相关的元信息
  202. schema(C) 执行 schema 命令检查指定类 C 是否存在
  203. count(N) 检查返回结果中的数据记录数是否为 N,N 为自然数
  204. equal(N,F,V) 判断返回结果中第 N 条数据的字段 F 的值是否为 V
  205. match(Kn,Mn) 检查返回结果中字段 Kn 值为 Mn 的记录是否存在,参数 Kn,Mn 可以有多个,需要成对出现
  206. matchcount(Kn,Mn,N) 检查返回结果中字段 Kn 值为 Mn 的记录数是否为 N,参数 Kn,Mn 可以有多个,需要成对出现,N为自然数
  207. 例:循环遍历执行当前路径下的所有 mql 文件
  208. ./mql .
  209. `)
  210. os.Exit(0)
  211. return
  212. }
  213. // 确定MODB连接
  214. if !assert.Nil(t, ODBError) {
  215. return
  216. }
  217. logger.Info("odbpath :", ODBC.Config().Hosts, ODBC.Config().Port)
  218. logger.Info("keyspace :", ODBC.Config().Keyspace)
  219. logger.Info("version :", ODBC.Versline())
  220. logger.Info("ksnative :", ksnative)
  221. logger.Info("debug :", debug)
  222. logger.Info("spath :", spath)
  223. // if checkCassSchema && !cass.CheckCassandraSchema(t) {
  224. // assert.True(t, false, "cassandra schemda is different")
  225. // return
  226. // }
  227. // 文件名以数字开头
  228. fnmatch := mcfg.CommandArgs.GetString("match", `^\d+.*`)
  229. fw, err := filewalker.NewFileWalker(spath, fnmatch) // orderby: dirfirst, filefirst, fullpath
  230. if !assert.Nil(t, err, err) {
  231. return
  232. }
  233. logger.Info("walkdir: ", fw.WalkDir)
  234. logger.Info("pathmatch: ", fw.RePath)
  235. logger.Info("filematch: ", fw.ReFile)
  236. // test
  237. fns := []string{}
  238. fw.List(func(basedir, fpath string) bool { fns = append(fns, filepath.Join(basedir, fpath)); return true })
  239. if len(fns) > 1 {
  240. appfile, err := filepath.Abs(os.Args[0])
  241. if !assert.Nil(t, err) {
  242. logger.Info("加锁时发生系统错误:", err)
  243. return
  244. }
  245. appdir := filepath.Dir(appfile)
  246. // 1. 创建一个锁对象(注意:这里传入的是锁文件的路径)
  247. fl := flock.New(filepath.Join(appdir, "mql.lock"))
  248. // 2. 尝试获取独占锁(写锁),不阻塞
  249. // 如果加锁失败(被其他进程占用),acquired 为 false,不会报错
  250. acquired, err := fl.TryLock()
  251. if !assert.Nil(t, err) {
  252. logger.Info("加锁时发生系统错误:", err)
  253. return
  254. }
  255. if !acquired {
  256. log.Println("无法获取测试锁,可能另一个测试实例正在运行")
  257. log.Println("can't lock test, another test is running")
  258. t.Fail()
  259. return
  260. }
  261. // 3. 务必在操作完成后解锁(使用 defer 确保执行)
  262. defer fl.Unlock()
  263. }
  264. logger.Info(fmt.Sprint("fns:", "\n", strings.Join(fns, "\n")))
  265. if len(fns) == 0 {
  266. logger.Info("没有找到 MQL 文件")
  267. return
  268. }
  269. logger.Info("共找到", len(fns), "个文件")
  270. // 顺序读取当前目录下文件名为数字开头的文件,执行其中的mql
  271. (&MQLTest{}).Run(t, fw)
  272. // 等待延迟显示信息输出
  273. // time.Sleep(1 * time.Second)
  274. logger.Info("关闭与服务器的连接")
  275. ODBC.Close()
  276. // 等待正常结束,只是为了发现隐含的问题
  277. // for n := 0; runtime.NumGoroutine() > 60 && n < 10; n++ {
  278. // fmt.Println("剩余协程数:", runtime.NumGoroutine())
  279. // time.Sleep(1000 * time.Millisecond)
  280. // }
  281. logger.Info("剩余协程数:", runtime.NumGoroutine())
  282. }
  283. // action(a1,a2...)
  284. // --注释后的大括号之间的内容 -- {}
  285. // mql query之后执行的动作
  286. var reactions = regexp.MustCompile(`(\w+)\s*\(([^\)]*)\)`)
  287. // 替换为随机可见字符
  288. var rereplace_nbytes = regexp.MustCompile(`\.\.\.\s*(\d+)\s*[Bb][Yy][Tt][Ee]s?\s*\.\.\.`)
  289. var reactioneexprs = regexp.MustCompile(`(?s)\/\*\*(?:\s*(\w+\s*\(\s*.*\)\s*)*)*\*\*\/`)
  290. var reactioneexprs_2 = regexp.MustCompile(`(?s)(?:(?:^|\n)\-\-\s*\{(.*)\}\s*)+$`)
  291. var reactioneexprs_3 = regexp.MustCompile(`(?s)(?:^\-\-\s*\{(.*)\}\s*)+\n`)
  292. var commentexprs = regexp.MustCompile(`(?s)\/\*(?:[^\*]|\*+[^\*\/])*\*+\/`)
  293. var commentexprs_2 = regexp.MustCompile(`(?ms)(?:^|\n)\-\-[^\n]*(?:\n|$)`)
  294. var commentexprs_3 = regexp.MustCompile(`(?ms)(?:^|\n)//[^\n]*(?:\n|$)`)
  295. type MQLTest struct {
  296. t *testing.T
  297. fw *filewalker.FileWalker
  298. scopevars *ScopeVars
  299. }
  300. type ScopeVars struct {
  301. sync.RWMutex
  302. top *Variables
  303. dir map[string]*Variables
  304. file map[string]*Variables
  305. mql map[string]*Variables
  306. }
  307. type Variables struct {
  308. vars map[string]interface{}
  309. loop_count int
  310. loop_from int
  311. loop_step int
  312. timeout time.Duration
  313. qmeta odb.QueryMeta
  314. parallel_max int
  315. }
  316. type CurrentVars struct {
  317. loop_i int
  318. ch_parallel_count chan<- int
  319. mqlcount int32
  320. sleeptime time.Duration
  321. totalusetime time.Duration
  322. maxusetime time.Duration
  323. minusetime time.Duration
  324. }
  325. type GlobalVars struct {
  326. sync.RWMutex
  327. *CurrentVars
  328. wg_wait_fork_routine map[string]*sync.WaitGroup
  329. ch_wait_mql_done map[string]chan bool
  330. }
  331. func (mt *MQLTest) Run(t *testing.T, fw *filewalker.FileWalker) (ok bool) {
  332. mt.t = t
  333. mt.fw = fw
  334. global := &GlobalVars{
  335. CurrentVars: &CurrentVars{},
  336. wg_wait_fork_routine: make(map[string]*sync.WaitGroup),
  337. ch_wait_mql_done: make(map[string]chan bool),
  338. }
  339. mt.scopevars = &ScopeVars{
  340. top: &Variables{
  341. vars: map[string]interface{}{},
  342. loop_count: 1,
  343. loop_from: 1,
  344. loop_step: 1},
  345. dir: map[string]*Variables{},
  346. file: map[string]*Variables{},
  347. mql: map[string]*Variables{}}
  348. ctx, cancel := context.WithCancel(context.Background())
  349. defer cancel()
  350. var wg sync.WaitGroup
  351. st := time.Now()
  352. loop_i := 0
  353. parallel_queue := pqc.NewQueue[any](0)
  354. mqlcount := int32(0)
  355. for {
  356. mt.scopevars.Lock()
  357. ok := loop_i < mt.scopevars.top.loop_count
  358. mt.scopevars.Unlock()
  359. if !ok {
  360. break
  361. }
  362. loop_i++
  363. //
  364. ch_parallel_count := make(chan int)
  365. topvars := &CurrentVars{
  366. loop_i: loop_i,
  367. ch_parallel_count: ch_parallel_count,
  368. }
  369. //
  370. ok_chan := make(chan bool, 1)
  371. parallel_chan := make(chan bool, 1)
  372. parallel := false
  373. parallelcount := 0
  374. done := false
  375. wg.Add(1)
  376. go func() {
  377. defer func() {
  378. atomic.AddInt32(&mqlcount, topvars.mqlcount)
  379. wg.Done()
  380. }()
  381. ch_ok := make(chan bool)
  382. go func() {
  383. for {
  384. select {
  385. case <-ch_parallel_count:
  386. if !done && !parallel {
  387. parallel = true
  388. // 加入并发控制队列
  389. if parallelcount > 0 {
  390. if parallelcount > parallel_queue.Size() {
  391. parallel_queue.Growth(parallelcount)
  392. }
  393. parallel_queue.Push(1)
  394. }
  395. parallel_chan <- true
  396. }
  397. case ok := <-ch_ok:
  398. ok_chan <- ok
  399. if parallel {
  400. if parallelcount > 0 {
  401. // 从并发控制队列中移除
  402. parallel_queue.Pop()
  403. }
  404. } else {
  405. done = true
  406. }
  407. return
  408. }
  409. }
  410. }()
  411. ok := mt.RunAll(t, ctx,
  412. global,
  413. topvars)
  414. ch_ok <- ok
  415. if !ok {
  416. cancel() // 并发测试,有一个线程出错,就全停
  417. return
  418. }
  419. }()
  420. success := true
  421. select {
  422. case success = <-ok_chan: // 非并发,等待完成
  423. case <-parallel_chan: // 并发,执行继续下一次
  424. logger.Info("第", topvars.loop_i, "次并发执行继续")
  425. }
  426. if !success {
  427. return false // 失败,不等,直接返回
  428. }
  429. }
  430. wg.Wait()
  431. mt.scopevars.RLock()
  432. loop_count := mt.scopevars.top.loop_count
  433. mt.scopevars.RUnlock()
  434. ut := time.Since(st)
  435. aut := time.Duration(0)
  436. if mqlcount > 0 {
  437. aut = global.totalusetime / time.Duration(mqlcount)
  438. }
  439. logger.Info("完成 ", loop_count, " 次执行,共", mqlcount, "次 MQL 请求,耗时", ut, "单条响应时间", global.minusetime, "~", global.maxusetime, "/", aut, "平均每秒吞吐量", (int64(mqlcount)*int64(time.Second))/int64(ut))
  440. return
  441. }
  442. func (mt *MQLTest) RunAll(t *testing.T, ctx context.Context, global *GlobalVars, topvars *CurrentVars) bool {
  443. logger.Info("开始第", topvars.loop_i, "次执行")
  444. st := time.Now()
  445. // 读取文件列表
  446. listdirs := []string{}
  447. dirfiles := map[string][]string{}
  448. err := mt.fw.List(func(basedir, filename string) bool {
  449. if dirfiles[basedir] == nil {
  450. listdirs = append(listdirs, basedir)
  451. }
  452. dirfiles[basedir] = append(dirfiles[basedir], filename)
  453. return true
  454. })
  455. if !assert.Nil(t, err, err) {
  456. return false
  457. }
  458. // 执行所有目录
  459. for _, basedir := range listdirs {
  460. // 循环执行目录下所有文件
  461. mt.scopevars.Lock()
  462. if mt.scopevars.dir[basedir] == nil {
  463. mt.scopevars.dir[basedir] = &Variables{
  464. vars: map[string]interface{}{},
  465. loop_count: 1,
  466. loop_from: 1,
  467. loop_step: 1}
  468. }
  469. mt.scopevars.Unlock()
  470. var wg sync.WaitGroup
  471. st := time.Now()
  472. loop_i := 0
  473. parallel_queue := pqc.NewQueue[any](0)
  474. mqlcount := int32(0)
  475. for {
  476. mt.scopevars.Lock()
  477. ok := loop_i < mt.scopevars.dir[basedir].loop_count
  478. mt.scopevars.Unlock()
  479. if !ok {
  480. break
  481. }
  482. loop_i++
  483. //
  484. ch_parallel_count := make(chan int)
  485. dirvars := &CurrentVars{
  486. loop_i: loop_i,
  487. ch_parallel_count: ch_parallel_count,
  488. }
  489. //
  490. ok_chan := make(chan bool, 1)
  491. parallel_chan := make(chan bool, 1)
  492. parallel := false
  493. parallelcount := 0
  494. done := false
  495. wg.Add(1)
  496. go func(basedir string) {
  497. defer func() {
  498. atomic.AddInt32(&mqlcount, dirvars.mqlcount)
  499. wg.Done()
  500. }()
  501. ch_ok := make(chan bool)
  502. go func() {
  503. for {
  504. select {
  505. case <-ch_parallel_count:
  506. if !done && !parallel {
  507. parallel = true
  508. // 加入并发控制队列
  509. if parallelcount > 0 {
  510. if parallelcount > parallel_queue.Size() {
  511. parallel_queue.Growth(parallelcount)
  512. }
  513. parallel_queue.Push(1)
  514. }
  515. parallel_chan <- true
  516. }
  517. case ok := <-ch_ok:
  518. ok_chan <- ok
  519. if parallel {
  520. if parallelcount > 0 {
  521. // 从并发控制队列中移除
  522. parallel_queue.Pop()
  523. }
  524. } else {
  525. done = true
  526. }
  527. return
  528. }
  529. }
  530. }()
  531. // logger.Info("dir", basedir, "第", fmt.Sprint(topvars.loop_i, ".", dirvars.loop_i), "次执行开始")
  532. files := dirfiles[basedir]
  533. ch_ok <- mt.RunDir(t, ctx,
  534. global,
  535. topvars,
  536. dirvars,
  537. basedir, files)
  538. // logger.Info("dir", basedir, "第", fmt.Sprint(topvars.loop_i, ".", dirvars.loop_i), "次执行结束")
  539. }(basedir)
  540. success := true
  541. select {
  542. case success = <-ok_chan: // 非并发,等待完成
  543. logger.Info("dir", basedir, "第", fmt.Sprint(topvars.loop_i, ".", dirvars.loop_i), "次顺序执行完成")
  544. case <-parallel_chan: // 并发,执行继续下一次
  545. logger.Info("dir", basedir, "第", fmt.Sprint(topvars.loop_i, ".", dirvars.loop_i), "次并发执行继续")
  546. }
  547. if !success {
  548. return false
  549. }
  550. }
  551. wg.Wait()
  552. mt.scopevars.RLock()
  553. loop_count := mt.scopevars.dir[basedir].loop_count
  554. mt.scopevars.RUnlock()
  555. if loop_count > 1 {
  556. ut := time.Since(st)
  557. logger.Info(fmt.Sprint("dir ", basedir, " loop ", loop_count, " times, run ", mqlcount, " mqls, usetime ", ut))
  558. }
  559. }
  560. logger.Info("完成第", topvars.loop_i, "次执行,共", topvars.mqlcount, "次 MQL 请求,耗时", time.Since(st))
  561. return true
  562. }
  563. func (mt *MQLTest) RunDir(t *testing.T, ctx context.Context,
  564. global *GlobalVars,
  565. topvars *CurrentVars,
  566. dirvars *CurrentVars,
  567. basedir string, files []string) bool {
  568. for _, filename := range files {
  569. ok := mt.RunFile(t, ctx, global, topvars, dirvars, basedir, filename)
  570. if !ok {
  571. return false
  572. }
  573. }
  574. return true
  575. }
  576. func (mt *MQLTest) RunFile(t *testing.T, ctx context.Context,
  577. global *GlobalVars,
  578. topvars *CurrentVars,
  579. dirvars *CurrentVars,
  580. basedir, filename string) bool {
  581. // 读取文件内容
  582. ffpath := filepath.Join(basedir, filename)
  583. bs, err := os.ReadFile(ffpath)
  584. if !assert.Nil(t, err, err) {
  585. return false
  586. }
  587. // mql语句切分
  588. mqgr := NewMQLGroupRequest()
  589. var multilines *MQLRequest
  590. mqs := spliter.NewMQLSpliter(bufio.NewReader(strings.NewReader(string(bs))))
  591. for {
  592. mql, fromline, toline, fromchar, tochar, hasnext, _ := mqs.NextMQL()
  593. if !hasnext {
  594. break
  595. }
  596. if multilines != nil {
  597. if strings.TrimSpace(mql) == "multilines end" {
  598. e := mqgr.Append(multilines)
  599. if !assert.Nil(t, e, e) {
  600. return false
  601. }
  602. multilines = nil
  603. } else if multilines.OriginQueryString == "" {
  604. multilines.OriginQueryString = mql
  605. multilines.Fromline = fromline
  606. multilines.Toline = toline
  607. multilines.Fromchar = fromchar
  608. multilines.Tochar = tochar
  609. } else {
  610. multilines.OriginQueryString += ";" + mql
  611. multilines.Toline = toline
  612. multilines.Tochar = tochar
  613. }
  614. } else if strings.TrimSpace(mql) == "multilines begin" {
  615. multilines = &MQLRequest{FilePath: ffpath}
  616. } else {
  617. mqr := &MQLRequest{OriginQueryString: mql, FilePath: ffpath, Fromline: fromline, Toline: toline, Fromchar: fromchar, Tochar: tochar}
  618. e := mqgr.Append(mqr)
  619. if !assert.Nil(t, e, e) {
  620. return false
  621. }
  622. }
  623. }
  624. // mqls := spliter.MQLSplit(string(bs))
  625. mt.scopevars.Lock()
  626. if mt.scopevars.file[ffpath] == nil {
  627. mt.scopevars.file[ffpath] = &Variables{
  628. vars: map[string]interface{}{},
  629. loop_count: 1,
  630. loop_from: 1,
  631. loop_step: 1}
  632. }
  633. mt.scopevars.Unlock()
  634. var wg sync.WaitGroup
  635. st := time.Now()
  636. loop_i := 0
  637. parallel_queue := pqc.NewQueue[any](0)
  638. mqlcount := int32(0)
  639. for {
  640. mt.scopevars.Lock()
  641. ok := loop_i < mt.scopevars.file[ffpath].loop_count
  642. mt.scopevars.Unlock()
  643. if !ok {
  644. break
  645. }
  646. loop_i++
  647. //
  648. ch_parallel_count := make(chan int)
  649. filevars := &CurrentVars{
  650. loop_i: loop_i,
  651. ch_parallel_count: ch_parallel_count,
  652. }
  653. //
  654. ok_chan := make(chan bool, 1)
  655. parallel_chan := make(chan bool, 1)
  656. parallel := false
  657. parallelcount := 0
  658. done := false
  659. wg.Add(1)
  660. go func() {
  661. defer func() {
  662. atomic.AddInt32(&mqlcount, filevars.mqlcount)
  663. wg.Done()
  664. }()
  665. ch_ok := make(chan bool)
  666. go func() {
  667. for {
  668. select {
  669. case <-ch_parallel_count:
  670. if !done && !parallel {
  671. parallel = true
  672. // 加入并发控制队列
  673. if parallelcount > 0 {
  674. if parallelcount > parallel_queue.Size() {
  675. parallel_queue.Growth(parallelcount)
  676. }
  677. parallel_queue.Push(1)
  678. }
  679. parallel_chan <- true
  680. }
  681. case ok := <-ch_ok:
  682. ok_chan <- ok
  683. if parallel {
  684. if parallelcount > 0 {
  685. // 从并发控制队列中移除
  686. parallel_queue.Pop()
  687. }
  688. } else {
  689. done = true
  690. }
  691. return
  692. }
  693. }
  694. }()
  695. // logger.Info("file", ffpath, "第", fmt.Sprint(topvars.loop_i, ".", dirvars.loop_i, ".", filevars.loop_i), "次执行开始")
  696. ch_ok <- mt.RunMQLGroup(t, ctx,
  697. global,
  698. topvars,
  699. dirvars,
  700. filevars,
  701. basedir, ffpath, mqgr)
  702. // logger.Info("file", ffpath, "第", fmt.Sprint(topvars.loop_i, ".", dirvars.loop_i, ".", filevars.loop_i), "次执行结束")
  703. }()
  704. success := true
  705. select {
  706. case success = <-ok_chan: // 非并发,等待完成
  707. logger.Info("file", ffpath, "第", fmt.Sprint(topvars.loop_i, ".", dirvars.loop_i, ".", filevars.loop_i), "次顺序执行完成")
  708. case <-parallel_chan: // 并发,执行继续下一次
  709. logger.Info("file", ffpath, "第", fmt.Sprint(topvars.loop_i, ".", dirvars.loop_i, ".", filevars.loop_i), "次并发执行继续")
  710. }
  711. if !success {
  712. return false
  713. }
  714. }
  715. wg.Wait()
  716. mt.scopevars.RLock()
  717. loop_count := mt.scopevars.file[ffpath].loop_count
  718. mt.scopevars.RUnlock()
  719. if loop_count > 1 {
  720. ut := time.Since(st)
  721. sn := fmt.Sprint(topvars.loop_i, ".", dirvars.loop_i)
  722. logger.Info(fmt.Sprint("file ", ffpath+"/"+sn, " loop ", loop_count, " times, run ", mqlcount, " mqls, usetime ", ut))
  723. }
  724. return true
  725. }
  726. func (mt *MQLTest) RunMQLGroup(t *testing.T, ctx context.Context,
  727. global *GlobalVars,
  728. topvars *CurrentVars,
  729. dirvars *CurrentVars,
  730. filevars *CurrentVars,
  731. basedir, ffpath string, mqgr *MQLGroupRequest) (pass bool) {
  732. pass = true
  733. var wg sync.WaitGroup
  734. for _, mqs := range mqgr.mqrs {
  735. wg.Add(1)
  736. go func(mqs []*MQLRequest) {
  737. defer wg.Done()
  738. if len(mqs) == 0 {
  739. return
  740. }
  741. if mqs[0].StaticActions.ForkName != nil {
  742. forkname := *mqs[0].StaticActions.ForkName
  743. global.Lock()
  744. wg := global.wg_wait_fork_routine[forkname]
  745. if wg == nil {
  746. wg = &sync.WaitGroup{}
  747. global.wg_wait_fork_routine[forkname] = wg
  748. }
  749. global.Unlock()
  750. wg.Add(1)
  751. defer wg.Done()
  752. }
  753. ok := mt.RunMQLs(t, ctx, global, topvars, dirvars, filevars, basedir, ffpath, mqs)
  754. if !ok {
  755. pass = false
  756. }
  757. }(mqs)
  758. }
  759. wg.Wait()
  760. return
  761. }
  762. func (mt *MQLTest) RunMQLs(t *testing.T, ctx context.Context,
  763. global *GlobalVars,
  764. topvars *CurrentVars,
  765. dirvars *CurrentVars,
  766. filevars *CurrentVars,
  767. basedir, ffpath string, mqrs []*MQLRequest) bool {
  768. for _, mqr := range mqrs {
  769. mqlkey := mqr.Key
  770. mqlstr := mqr.OriginQueryString
  771. if mqlstr == "" {
  772. continue
  773. }
  774. staticactions := mqr.StaticActions
  775. // 设置执行过程中的控制参数
  776. mt.InitScopeVars(basedir, ffpath, mqlkey, staticactions)
  777. ch_test_run_one_mql_result := make(chan bool)
  778. go func() {
  779. mqrinst := fmt.Sprint(mqlkey, "/", topvars.loop_i, ".", dirvars.loop_i, ".", filevars.loop_i)
  780. global.Lock()
  781. mqrdone := global.ch_wait_mql_done[mqrinst]
  782. if mqrdone == nil {
  783. mqrdone = make(chan bool)
  784. global.ch_wait_mql_done[mqrinst] = mqrdone
  785. }
  786. var waitmqrdone chan bool
  787. if mqr.WaitMQLRequest != nil {
  788. waitmqrkey := mqr.WaitMQLRequest.Key
  789. waitmqrinst := fmt.Sprint(waitmqrkey, "/", topvars.loop_i, ".", dirvars.loop_i, ".", filevars.loop_i)
  790. waitmqrdone = global.ch_wait_mql_done[waitmqrinst]
  791. if waitmqrdone == nil {
  792. waitmqrdone = make(chan bool)
  793. global.ch_wait_mql_done[waitmqrinst] = waitmqrdone
  794. }
  795. }
  796. global.Unlock()
  797. var ret bool
  798. defer func() { mqrdone <- ret }()
  799. if waitmqrdone != nil {
  800. v := <-waitmqrdone
  801. waitmqrdone <- v
  802. if !v {
  803. // 依赖MQR失败
  804. ch_test_run_one_mql_result <- false
  805. return
  806. }
  807. }
  808. ret = mt.RunMQR(t, ctx, global, topvars, dirvars, filevars, basedir, ffpath, mqr)
  809. ch_test_run_one_mql_result <- ret
  810. }()
  811. ret := <-ch_test_run_one_mql_result
  812. if !ret {
  813. return ret
  814. }
  815. // continue
  816. }
  817. return true
  818. }
  819. func (mt *MQLTest) RunMQR(t *testing.T, ctx context.Context,
  820. global *GlobalVars,
  821. topvars *CurrentVars,
  822. dirvars *CurrentVars,
  823. filevars *CurrentVars,
  824. basedir, ffpath string, mqr *MQLRequest) bool {
  825. mqlkey := mqr.Key
  826. staticactionexprs := mqr.StaticActionExprs
  827. staticactions := mqr.StaticActions
  828. return t.Run(mqlkey, func(t *testing.T) {
  829. var wg sync.WaitGroup
  830. st := time.Now()
  831. loop_i := 0
  832. parallel_queue := pqc.NewQueue[any](0)
  833. mqlcount := int32(0)
  834. for {
  835. mt.scopevars.Lock()
  836. ok := loop_i < mt.scopevars.mql[mqlkey].loop_count
  837. mt.scopevars.Unlock()
  838. if !ok {
  839. break
  840. }
  841. loop_i++
  842. //
  843. ch_parallel_count := make(chan int)
  844. mqlvars := &CurrentVars{
  845. loop_i: loop_i,
  846. ch_parallel_count: ch_parallel_count,
  847. }
  848. // 运行实例
  849. mqlsn := fmt.Sprint(mqlkey, "/", topvars.loop_i, ".", dirvars.loop_i, ".", filevars.loop_i, ".", mqlvars.loop_i)
  850. mt.scopevars.Lock()
  851. if mt.scopevars.mql[mqlsn] == nil {
  852. mt.scopevars.mql[mqlsn] = &Variables{
  853. vars: map[string]interface{}{},
  854. loop_count: 1,
  855. loop_from: 1,
  856. loop_step: 1}
  857. }
  858. mt.scopevars.Unlock()
  859. //
  860. mt.scopevars.Lock()
  861. top_loopi := mt.scopevars.top.loop_from + (topvars.loop_i-1)*mt.scopevars.top.loop_step
  862. mt.scopevars.top.vars["topi"] = top_loopi
  863. dir_loopi := mt.scopevars.dir[basedir].loop_from + (dirvars.loop_i-1)*mt.scopevars.dir[basedir].loop_step
  864. mt.scopevars.dir[basedir].vars["diri"] = dir_loopi
  865. mt.scopevars.dir[basedir].vars["topi"] = top_loopi
  866. file_loopi := mt.scopevars.file[ffpath].loop_from + (filevars.loop_i-1)*mt.scopevars.file[ffpath].loop_step
  867. mt.scopevars.file[ffpath].vars["filei"] = file_loopi
  868. mt.scopevars.file[ffpath].vars["diri"] = dir_loopi
  869. mt.scopevars.file[ffpath].vars["topi"] = top_loopi
  870. mql_loopi := mt.scopevars.mql[mqlkey].loop_from + (mqlvars.loop_i-1)*mt.scopevars.mql[mqlkey].loop_step
  871. mt.scopevars.mql[mqlkey].vars["mqli"] = mql_loopi
  872. mt.scopevars.mql[mqlkey].vars["filei"] = file_loopi
  873. mt.scopevars.mql[mqlkey].vars["diri"] = dir_loopi
  874. mt.scopevars.mql[mqlkey].vars["topi"] = top_loopi
  875. //
  876. mt.scopevars.mql[mqlsn].vars["mqli"] = mql_loopi
  877. mt.scopevars.mql[mqlsn].vars["filei"] = file_loopi
  878. mt.scopevars.mql[mqlsn].vars["diri"] = dir_loopi
  879. mt.scopevars.mql[mqlsn].vars["topi"] = top_loopi
  880. mt.scopevars.Unlock()
  881. mt.BeforeRunAction(basedir, ffpath, mqlkey, mqlsn, staticactions)
  882. formatedmqlstr := mqr.FormatedQueryString
  883. mql := mt.ReplaceLoopSN(formatedmqlstr,
  884. global, topvars, dirvars, filevars, mqlvars,
  885. top_loopi, dir_loopi, file_loopi, mql_loopi,
  886. basedir, ffpath, mqlkey, mqlsn,
  887. )
  888. mqlreplace := rereplace_nbytes.FindAllStringSubmatch(mql, -1)
  889. for _, mqr := range mqlreplace {
  890. if len(mqr) == 2 {
  891. bs := make([]byte, cast.ToInt(mqr[1]))
  892. for i := 0; i < len(bs); i++ {
  893. bs[i] = byte(32 + rand.Intn(91))
  894. }
  895. s := string(bs)
  896. s = strings.ReplaceAll(s, ")", string([]byte{123}))
  897. s = strings.ReplaceAll(s, "'", string([]byte{124}))
  898. s = strings.ReplaceAll(s, "\"", string([]byte{125}))
  899. s = strings.ReplaceAll(s, "\\", string([]byte{126}))
  900. mql = strings.Replace(mql, mqr[0], s, 1)
  901. }
  902. }
  903. for i, sat := range staticactionexprs {
  904. mql = strings.Replace(mql, "["+strconv.Itoa(i)+"]", sat.SourceText, 1)
  905. }
  906. mql = strings.ReplaceAll(mql, "[[]", "[")
  907. mqri := &MQLRequestInstance{
  908. MQLRequest: mqr,
  909. PreparedQueryString: mql,
  910. }
  911. //
  912. ok_chan := make(chan error, 1)
  913. parallel_chan := make(chan bool, 1)
  914. parallel := false
  915. parallelcount := 0
  916. done := false
  917. wg.Add(1)
  918. go func(mqlvars *CurrentVars) {
  919. defer func() {
  920. atomic.AddInt32(&mqlcount, mqlvars.mqlcount)
  921. wg.Done()
  922. }()
  923. ch_ok := make(chan error)
  924. go func() {
  925. for {
  926. select {
  927. case parallelcount = <-ch_parallel_count:
  928. if !done && !parallel {
  929. parallel = true
  930. // 加入并发控制队列
  931. if parallelcount > 0 {
  932. if parallelcount > parallel_queue.Size() {
  933. parallel_queue.Growth(parallelcount)
  934. }
  935. parallel_queue.Push(1)
  936. }
  937. parallel_chan <- true
  938. }
  939. case ok := <-ch_ok:
  940. ok_chan <- ok
  941. if parallel {
  942. if parallelcount > 0 {
  943. // 从并发控制队列中移除
  944. parallel_queue.Pop()
  945. }
  946. } else {
  947. done = true
  948. }
  949. return
  950. }
  951. }
  952. }()
  953. nstaticactionexprs := map[int]*Action{}
  954. for i, sat := range staticactionexprs {
  955. nstaticactionexprs[i] = sat
  956. }
  957. // logger.Info(mqlkey, "第", fmt.Sprint(all_loop_i, ".", dir_loop_i, ".", file_loop_i, ".", curval.mql_i), "次执行开始")
  958. ch_ok <- mt.RunMQL(t, ctx,
  959. global,
  960. topvars,
  961. dirvars,
  962. filevars,
  963. mqlvars,
  964. basedir, ffpath, mqlkey, mqlsn, mqri, staticactions, nstaticactionexprs)
  965. // logger.Info(mqlkey, "第", fmt.Sprint(all_loop_i, ".", dir_loop_i, ".", file_loop_i, ".", curval.mql_i), "次执行结束")
  966. }(mqlvars)
  967. var err error
  968. select {
  969. case err = <-ok_chan: // 非并发,等待完成
  970. // logger.Info(mqlkey, "第", fmt.Sprint(all_loop_i, ".", dir_loop_i, ".", file_loop_i, ".", curval.mql_i), "次顺序执行完成")
  971. case <-parallel_chan: // 并发,执行继续下一次
  972. // logger.Info(mqlkey, "第", fmt.Sprint(all_loop_i, ".", dir_loop_i, ".", file_loop_i, ".", curval.mql_i), "次并发执行继续")
  973. }
  974. if err != nil {
  975. // logger.Error(err)
  976. break
  977. }
  978. }
  979. wg.Wait()
  980. mt.scopevars.RLock()
  981. loop_count := mt.scopevars.mql[mqlkey].loop_count
  982. mt.scopevars.RUnlock()
  983. if loop_count > 1 {
  984. ut := time.Since(st)
  985. sn := fmt.Sprint(topvars.loop_i, ".", dirvars.loop_i, ".", filevars.loop_i)
  986. as := ""
  987. if topvars.sleeptime > 0 {
  988. as = fmt.Sprint(", sleep ", topvars.sleeptime)
  989. }
  990. logger.Info(fmt.Sprint("mql ", mqlkey+"/"+sn, " loop ", loop_i, " times, usetime ", ut, as))
  991. }
  992. })
  993. }
  994. func (mt *MQLTest) getValue(basedir, ffpath, mqlkey, mqlsn string,
  995. staticactions *StaticActions, a any) (ak string, va any) {
  996. switch av := a.(type) {
  997. case *Action:
  998. switch av.Name {
  999. case "<EQ>":
  1000. if len(av.Args) >= 2 {
  1001. _, x := mt.getValue(basedir, ffpath, mqlkey, mqlsn, staticactions, av.Args[0])
  1002. _, y := mt.getValue(basedir, ffpath, mqlkey, mqlsn, staticactions, av.Args[1])
  1003. if cast.ToString(x) == cast.ToString(y) {
  1004. return "", true
  1005. }
  1006. }
  1007. return "", false
  1008. }
  1009. case *qstru.Expr:
  1010. ak = av.VarName
  1011. if ak == "now" {
  1012. return "", time.Now()
  1013. }
  1014. mt.scopevars.Lock()
  1015. switch staticactions.Scope {
  1016. case "top":
  1017. va = mt.scopevars.top.vars[ak]
  1018. case "dir":
  1019. va = mt.scopevars.dir[basedir].vars[ak]
  1020. case "file":
  1021. va = mt.scopevars.file[ffpath].vars[ak]
  1022. default:
  1023. var has bool
  1024. va, has = mt.scopevars.mql[mqlsn].vars[ak]
  1025. if !has {
  1026. va = mt.scopevars.mql[mqlkey].vars[ak]
  1027. }
  1028. }
  1029. mt.scopevars.Unlock()
  1030. case string:
  1031. va = av
  1032. for _, tf := range time_layouts {
  1033. t, e := time.Parse(tf, av)
  1034. if e == nil {
  1035. va = t
  1036. break
  1037. }
  1038. }
  1039. default:
  1040. va = a
  1041. }
  1042. return
  1043. }
  1044. func (mt *MQLTest) setValue(basedir, ffpath, mqlkey, mqlsn string,
  1045. staticactions *StaticActions, ak string, va any) {
  1046. mt.scopevars.Lock()
  1047. switch staticactions.Scope {
  1048. case "top":
  1049. mt.scopevars.top.vars[ak] = va
  1050. case "dir":
  1051. mt.scopevars.dir[basedir].vars[ak] = va
  1052. case "file":
  1053. mt.scopevars.file[ffpath].vars[ak] = va
  1054. default:
  1055. _, has := mt.scopevars.mql[mqlsn].vars[ak]
  1056. if has {
  1057. mt.scopevars.mql[mqlsn].vars[ak] = va
  1058. } else {
  1059. mt.scopevars.mql[mqlkey].vars[ak] = va
  1060. }
  1061. }
  1062. mt.scopevars.Unlock()
  1063. }
  1064. func (mt *MQLTest) BeforeRunAction(basedir, ffpath, mqlkey, mqlsn string,
  1065. staticactions *StaticActions,
  1066. ) {
  1067. mt.runAction(basedir, ffpath, mqlkey, mqlsn, staticactions, staticactions.BeforeRunActions...)
  1068. }
  1069. func (mt *MQLTest) runAction(basedir, ffpath, mqlkey, mqlsn string,
  1070. staticactions *StaticActions, actions ...*Action,
  1071. ) {
  1072. for _, act := range actions {
  1073. switch act.Name {
  1074. case "set":
  1075. var a, b any
  1076. var ak string
  1077. if len(act.Args) > 1 {
  1078. a = act.Args[0]
  1079. b = act.Args[1]
  1080. }
  1081. ak, _ = mt.getValue(basedir, ffpath, mqlkey, mqlsn, staticactions, a)
  1082. _, vb := mt.getValue(basedir, ffpath, mqlkey, mqlsn, staticactions, b)
  1083. mt.setValue(basedir, ffpath, mqlkey, mqlsn, staticactions, ak, vb)
  1084. case "add":
  1085. var a, b, va, vb any
  1086. var ak string
  1087. if len(act.Args) > 1 {
  1088. a = act.Args[0]
  1089. b = act.Args[1]
  1090. }
  1091. ak, va = mt.getValue(basedir, ffpath, mqlkey, mqlsn, staticactions, a)
  1092. _, vb = mt.getValue(basedir, ffpath, mqlkey, mqlsn, staticactions, b)
  1093. switch v := va.(type) {
  1094. case time.Time:
  1095. unit := "second"
  1096. if len(act.Args) > 2 {
  1097. unit = cast.ToString(act.Args[2])
  1098. }
  1099. vb := cast.ToInt(vb)
  1100. d := time.Duration(0)
  1101. switch unit {
  1102. case "second", "seconds", "s", "秒":
  1103. d = time.Duration(vb) * time.Second
  1104. case "minute", "minutes", "m", "分":
  1105. d = time.Duration(vb) * time.Minute
  1106. case "hour", "hours", "h", "时":
  1107. d = time.Duration(vb) * time.Hour
  1108. }
  1109. v = v.Add(d)
  1110. mt.setValue(basedir, ffpath, mqlkey, mqlsn, staticactions, ak, v)
  1111. }
  1112. case "mod":
  1113. var a, b, va, vb any
  1114. var ak string
  1115. if len(act.Args) > 1 {
  1116. a = act.Args[0]
  1117. b = act.Args[1]
  1118. }
  1119. ak, va = mt.getValue(basedir, ffpath, mqlkey, mqlsn, staticactions, a)
  1120. _, vb = mt.getValue(basedir, ffpath, mqlkey, mqlsn, staticactions, b)
  1121. av := cast.ToInt(va)
  1122. bv := cast.ToInt(vb)
  1123. v := av % bv
  1124. mt.setValue(basedir, ffpath, mqlkey, mqlsn, staticactions, ak, v)
  1125. case "case":
  1126. var a, b, va any
  1127. if len(act.Args) > 1 {
  1128. a = act.Args[0]
  1129. b = act.Args[1]
  1130. }
  1131. _, va = mt.getValue(basedir, ffpath, mqlkey, mqlsn, staticactions, a)
  1132. if cast.ToBool(va) {
  1133. switch vb := b.(type) {
  1134. case *Action:
  1135. mt.runAction(basedir, ffpath, mqlkey, mqlsn, staticactions, vb)
  1136. }
  1137. }
  1138. }
  1139. }
  1140. }
  1141. func (mt *MQLTest) InitScopeVars(basedir, ffpath, mqlkey string,
  1142. staticactions *StaticActions,
  1143. ) {
  1144. mt.scopevars.Lock()
  1145. if mt.scopevars.mql[mqlkey] == nil {
  1146. mt.scopevars.mql[mqlkey] = &Variables{
  1147. vars: map[string]interface{}{},
  1148. loop_count: 1,
  1149. loop_from: 1,
  1150. loop_step: 1}
  1151. }
  1152. mt.scopevars.Unlock()
  1153. for k, v := range staticactions.Variables {
  1154. mt.scopevars.Lock()
  1155. switch staticactions.Scope {
  1156. case "top":
  1157. mt.scopevars.top.vars[k] = v
  1158. case "dir":
  1159. mt.scopevars.dir[basedir].vars[k] = v
  1160. case "file":
  1161. mt.scopevars.file[ffpath].vars[k] = v
  1162. default:
  1163. mt.scopevars.mql[mqlkey].vars[k] = v
  1164. }
  1165. mt.scopevars.Unlock()
  1166. }
  1167. if staticactions.Timeout != nil {
  1168. mt.scopevars.Lock()
  1169. switch staticactions.Scope {
  1170. case "top":
  1171. mt.scopevars.top.timeout = *staticactions.Timeout
  1172. case "dir":
  1173. mt.scopevars.dir[basedir].timeout = *staticactions.Timeout
  1174. case "file":
  1175. mt.scopevars.file[ffpath].timeout = *staticactions.Timeout
  1176. default:
  1177. mt.scopevars.mql[mqlkey].timeout = *staticactions.Timeout
  1178. }
  1179. mt.scopevars.Unlock()
  1180. }
  1181. if staticactions.Qmeta != nil {
  1182. mt.scopevars.Lock()
  1183. switch staticactions.Scope {
  1184. case "top":
  1185. mt.scopevars.top.qmeta = staticactions.Qmeta
  1186. case "dir":
  1187. mt.scopevars.dir[basedir].qmeta = staticactions.Qmeta
  1188. case "file":
  1189. mt.scopevars.file[ffpath].qmeta = staticactions.Qmeta
  1190. default:
  1191. mt.scopevars.mql[mqlkey].qmeta = staticactions.Qmeta
  1192. }
  1193. mt.scopevars.Unlock()
  1194. }
  1195. if staticactions.LoopCount != nil {
  1196. mt.scopevars.Lock()
  1197. switch staticactions.Scope {
  1198. case "top":
  1199. mt.scopevars.top.loop_count = *staticactions.LoopCount
  1200. case "dir":
  1201. mt.scopevars.dir[basedir].loop_count = *staticactions.LoopCount
  1202. case "file":
  1203. mt.scopevars.file[ffpath].loop_count = *staticactions.LoopCount
  1204. default:
  1205. mt.scopevars.mql[mqlkey].loop_count = *staticactions.LoopCount
  1206. }
  1207. mt.scopevars.Unlock()
  1208. }
  1209. if staticactions.LoopFrom != nil {
  1210. mt.scopevars.Lock()
  1211. switch staticactions.Scope {
  1212. case "top":
  1213. mt.scopevars.top.loop_from = *staticactions.LoopFrom
  1214. case "dir":
  1215. mt.scopevars.dir[basedir].loop_from = *staticactions.LoopFrom
  1216. case "file":
  1217. mt.scopevars.file[ffpath].loop_from = *staticactions.LoopFrom
  1218. default:
  1219. mt.scopevars.mql[mqlkey].loop_from = *staticactions.LoopFrom
  1220. }
  1221. mt.scopevars.Unlock()
  1222. }
  1223. if staticactions.LoopStep != nil {
  1224. mt.scopevars.Lock()
  1225. switch staticactions.Scope {
  1226. case "top":
  1227. mt.scopevars.top.loop_step = *staticactions.LoopStep
  1228. case "dir":
  1229. mt.scopevars.dir[basedir].loop_step = *staticactions.LoopStep
  1230. case "file":
  1231. mt.scopevars.file[ffpath].loop_step = *staticactions.LoopStep
  1232. default:
  1233. mt.scopevars.mql[mqlkey].loop_step = *staticactions.LoopStep
  1234. }
  1235. mt.scopevars.Unlock()
  1236. }
  1237. }
  1238. func (mt *MQLTest) RunMQL(t *testing.T, ctx context.Context,
  1239. global *GlobalVars,
  1240. topvars *CurrentVars,
  1241. dirvars *CurrentVars,
  1242. filevars *CurrentVars,
  1243. mqlvars *CurrentVars,
  1244. basedir, ffpath, mqlkey, mqlsn string, mqri *MQLRequestInstance, staticactions *StaticActions, staticactionexprs map[int]*Action) error {
  1245. mqlstr := mqri.PreparedQueryString
  1246. if staticactions.WaitName != nil {
  1247. global.Lock()
  1248. wgs := []*sync.WaitGroup{}
  1249. if *staticactions.WaitName == "" {
  1250. for _, wg := range global.wg_wait_fork_routine {
  1251. wgs = append(wgs, wg)
  1252. }
  1253. } else {
  1254. wg := global.wg_wait_fork_routine[*staticactions.WaitName]
  1255. if wg != nil {
  1256. wgs = append(wgs, wg)
  1257. }
  1258. }
  1259. global.Unlock()
  1260. for _, wg := range wgs {
  1261. wg.Wait()
  1262. }
  1263. }
  1264. if staticactions.ParallelCount != nil {
  1265. mt.scopevars.Lock()
  1266. switch staticactions.Scope {
  1267. case "top":
  1268. topvars.ch_parallel_count <- *staticactions.ParallelCount
  1269. case "dir":
  1270. dirvars.ch_parallel_count <- *staticactions.ParallelCount
  1271. case "file":
  1272. filevars.ch_parallel_count <- *staticactions.ParallelCount
  1273. default:
  1274. mqlvars.ch_parallel_count <- *staticactions.ParallelCount
  1275. }
  1276. mt.scopevars.Unlock()
  1277. }
  1278. // 重新获取修正后的动作
  1279. actionexprs, e := getActionExprs(mqlstr, staticactionexprs)
  1280. if !assert.Nil(t, e, e) {
  1281. return e
  1282. }
  1283. dynamicactions := actionexprs.DynamicActions()
  1284. if len(dynamicactions.SubscribeArgs) > 0 {
  1285. subscribe(dynamicactions.SubscribeArgs...)
  1286. }
  1287. if len(dynamicactions.UnsubscribeArgs) > 0 {
  1288. unsubscribe(dynamicactions.UnsubscribeArgs...)
  1289. }
  1290. values := []interface{}{}
  1291. if len(dynamicactions.Params) > 0 {
  1292. err := json.Unmarshal([]byte(dynamicactions.Params), &values)
  1293. if err != nil {
  1294. assert.Nil(t, fmt.Sprint("params参数只支持JSON Array,", dynamicactions.Params, mqlstr), err)
  1295. return err
  1296. }
  1297. }
  1298. x := atomic.AddInt32(&global.mqlcount, 1)
  1299. atomic.AddInt32(&topvars.mqlcount, 1)
  1300. atomic.AddInt32(&dirvars.mqlcount, 1)
  1301. atomic.AddInt32(&filevars.mqlcount, 1)
  1302. atomic.AddInt32(&mqlvars.mqlcount, 1)
  1303. err := mt.RunMQLTryDo(t, ctx,
  1304. global,
  1305. topvars,
  1306. dirvars,
  1307. filevars,
  1308. mqlvars,
  1309. basedir, ffpath, mqlkey, mqlsn+"("+strconv.Itoa(int(x))+")", mqri, values, staticactions, actionexprs)
  1310. if err != nil {
  1311. // 执行过程有错,停止继续执行
  1312. return err
  1313. }
  1314. if staticactions.SleepTime != nil {
  1315. global.sleeptime += *staticactions.SleepTime
  1316. topvars.sleeptime += *staticactions.SleepTime
  1317. dirvars.sleeptime += *staticactions.SleepTime
  1318. filevars.sleeptime += *staticactions.SleepTime
  1319. mqlvars.sleeptime += *staticactions.SleepTime
  1320. time.Sleep(*staticactions.SleepTime)
  1321. }
  1322. return nil
  1323. }