mql_run.go 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372
  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. return
  258. }
  259. // 3. 务必在操作完成后解锁(使用 defer 确保执行)
  260. defer fl.Unlock()
  261. }
  262. logger.Info(fmt.Sprint("fns:", "\n", strings.Join(fns, "\n")))
  263. if len(fns) == 0 {
  264. logger.Info("没有找到 MQL 文件")
  265. return
  266. }
  267. logger.Info("共找到", len(fns), "个文件")
  268. // 顺序读取当前目录下文件名为数字开头的文件,执行其中的mql
  269. (&MQLTest{}).Run(t, fw)
  270. // 等待延迟显示信息输出
  271. // time.Sleep(1 * time.Second)
  272. logger.Info("关闭与服务器的连接")
  273. ODBC.Close()
  274. // 等待正常结束,只是为了发现隐含的问题
  275. // for n := 0; runtime.NumGoroutine() > 60 && n < 10; n++ {
  276. // fmt.Println("剩余协程数:", runtime.NumGoroutine())
  277. // time.Sleep(1000 * time.Millisecond)
  278. // }
  279. logger.Info("剩余协程数:", runtime.NumGoroutine())
  280. }
  281. // action(a1,a2...)
  282. // --注释后的大括号之间的内容 -- {}
  283. // mql query之后执行的动作
  284. var reactions = regexp.MustCompile(`(\w+)\s*\(([^\)]*)\)`)
  285. // 替换为随机可见字符
  286. var rereplace_nbytes = regexp.MustCompile(`\.\.\.\s*(\d+)\s*[Bb][Yy][Tt][Ee]s?\s*\.\.\.`)
  287. var reactioneexprs = regexp.MustCompile(`(?s)\/\*\*(?:\s*(\w+\s*\(\s*.*\)\s*)*)*\*\*\/`)
  288. var reactioneexprs_2 = regexp.MustCompile(`(?s)(?:(?:^|\n)\-\-\s*\{(.*)\}\s*)+$`)
  289. var reactioneexprs_3 = regexp.MustCompile(`(?s)(?:^\-\-\s*\{(.*)\}\s*)+\n`)
  290. var commentexprs = regexp.MustCompile(`(?s)\/\*(?:[^\*]|\*+[^\*\/])*\*+\/`)
  291. var commentexprs_2 = regexp.MustCompile(`(?ms)(?:^|\n)\-\-[^\n]*(?:\n|$)`)
  292. var commentexprs_3 = regexp.MustCompile(`(?ms)(?:^|\n)//[^\n]*(?:\n|$)`)
  293. type MQLTest struct {
  294. t *testing.T
  295. fw *filewalker.FileWalker
  296. scopevars *ScopeVars
  297. }
  298. type ScopeVars struct {
  299. sync.RWMutex
  300. top *Variables
  301. dir map[string]*Variables
  302. file map[string]*Variables
  303. mql map[string]*Variables
  304. }
  305. type Variables struct {
  306. vars map[string]interface{}
  307. loop_count int
  308. loop_from int
  309. loop_step int
  310. timeout time.Duration
  311. qmeta odb.QueryMeta
  312. parallel_max int
  313. }
  314. type CurrentVars struct {
  315. loop_i int
  316. ch_parallel_count chan<- int
  317. mqlcount int32
  318. sleeptime time.Duration
  319. totalusetime time.Duration
  320. maxusetime time.Duration
  321. minusetime time.Duration
  322. }
  323. type GlobalVars struct {
  324. sync.RWMutex
  325. *CurrentVars
  326. wg_wait_fork_routine map[string]*sync.WaitGroup
  327. ch_wait_mql_done map[string]chan bool
  328. }
  329. func (mt *MQLTest) Run(t *testing.T, fw *filewalker.FileWalker) (ok bool) {
  330. mt.t = t
  331. mt.fw = fw
  332. global := &GlobalVars{
  333. CurrentVars: &CurrentVars{},
  334. wg_wait_fork_routine: make(map[string]*sync.WaitGroup),
  335. ch_wait_mql_done: make(map[string]chan bool),
  336. }
  337. mt.scopevars = &ScopeVars{
  338. top: &Variables{
  339. vars: map[string]interface{}{},
  340. loop_count: 1,
  341. loop_from: 1,
  342. loop_step: 1},
  343. dir: map[string]*Variables{},
  344. file: map[string]*Variables{},
  345. mql: map[string]*Variables{}}
  346. ctx, cancel := context.WithCancel(context.Background())
  347. defer cancel()
  348. var wg sync.WaitGroup
  349. st := time.Now()
  350. loop_i := 0
  351. parallel_queue := pqc.NewQueue[any](0)
  352. mqlcount := int32(0)
  353. for {
  354. mt.scopevars.Lock()
  355. ok := loop_i < mt.scopevars.top.loop_count
  356. mt.scopevars.Unlock()
  357. if !ok {
  358. break
  359. }
  360. loop_i++
  361. //
  362. ch_parallel_count := make(chan int)
  363. topvars := &CurrentVars{
  364. loop_i: loop_i,
  365. ch_parallel_count: ch_parallel_count,
  366. }
  367. //
  368. ok_chan := make(chan bool, 1)
  369. parallel_chan := make(chan bool, 1)
  370. parallel := false
  371. parallelcount := 0
  372. done := false
  373. wg.Add(1)
  374. go func() {
  375. defer func() {
  376. atomic.AddInt32(&mqlcount, topvars.mqlcount)
  377. wg.Done()
  378. }()
  379. ch_ok := make(chan bool)
  380. go func() {
  381. for {
  382. select {
  383. case <-ch_parallel_count:
  384. if !done && !parallel {
  385. parallel = true
  386. // 加入并发控制队列
  387. if parallelcount > 0 {
  388. if parallelcount > parallel_queue.Size() {
  389. parallel_queue.Growth(parallelcount)
  390. }
  391. parallel_queue.Push(1)
  392. }
  393. parallel_chan <- true
  394. }
  395. case ok := <-ch_ok:
  396. ok_chan <- ok
  397. if parallel {
  398. if parallelcount > 0 {
  399. // 从并发控制队列中移除
  400. parallel_queue.Pop()
  401. }
  402. } else {
  403. done = true
  404. }
  405. return
  406. }
  407. }
  408. }()
  409. ok := mt.RunAll(t, ctx,
  410. global,
  411. topvars)
  412. ch_ok <- ok
  413. if !ok {
  414. cancel() // 并发测试,有一个线程出错,就全停
  415. return
  416. }
  417. }()
  418. success := true
  419. select {
  420. case success = <-ok_chan: // 非并发,等待完成
  421. case <-parallel_chan: // 并发,执行继续下一次
  422. logger.Info("第", topvars.loop_i, "次并发执行继续")
  423. }
  424. if !success {
  425. return false // 失败,不等,直接返回
  426. }
  427. }
  428. wg.Wait()
  429. mt.scopevars.RLock()
  430. loop_count := mt.scopevars.top.loop_count
  431. mt.scopevars.RUnlock()
  432. ut := time.Since(st)
  433. aut := time.Duration(0)
  434. if mqlcount > 0 {
  435. aut = global.totalusetime / time.Duration(mqlcount)
  436. }
  437. logger.Info("完成 ", loop_count, " 次执行,共", mqlcount, "次 MQL 请求,耗时", ut, "单条响应时间", global.minusetime, "~", global.maxusetime, "/", aut, "平均每秒吞吐量", (int64(mqlcount)*int64(time.Second))/int64(ut))
  438. return
  439. }
  440. func (mt *MQLTest) RunAll(t *testing.T, ctx context.Context, global *GlobalVars, topvars *CurrentVars) bool {
  441. logger.Info("开始第", topvars.loop_i, "次执行")
  442. st := time.Now()
  443. // 读取文件列表
  444. listdirs := []string{}
  445. dirfiles := map[string][]string{}
  446. err := mt.fw.List(func(basedir, filename string) bool {
  447. if dirfiles[basedir] == nil {
  448. listdirs = append(listdirs, basedir)
  449. }
  450. dirfiles[basedir] = append(dirfiles[basedir], filename)
  451. return true
  452. })
  453. if !assert.Nil(t, err, err) {
  454. return false
  455. }
  456. // 执行所有目录
  457. for _, basedir := range listdirs {
  458. // 循环执行目录下所有文件
  459. mt.scopevars.Lock()
  460. if mt.scopevars.dir[basedir] == nil {
  461. mt.scopevars.dir[basedir] = &Variables{
  462. vars: map[string]interface{}{},
  463. loop_count: 1,
  464. loop_from: 1,
  465. loop_step: 1}
  466. }
  467. mt.scopevars.Unlock()
  468. var wg sync.WaitGroup
  469. st := time.Now()
  470. loop_i := 0
  471. parallel_queue := pqc.NewQueue[any](0)
  472. mqlcount := int32(0)
  473. for {
  474. mt.scopevars.Lock()
  475. ok := loop_i < mt.scopevars.dir[basedir].loop_count
  476. mt.scopevars.Unlock()
  477. if !ok {
  478. break
  479. }
  480. loop_i++
  481. //
  482. ch_parallel_count := make(chan int)
  483. dirvars := &CurrentVars{
  484. loop_i: loop_i,
  485. ch_parallel_count: ch_parallel_count,
  486. }
  487. //
  488. ok_chan := make(chan bool, 1)
  489. parallel_chan := make(chan bool, 1)
  490. parallel := false
  491. parallelcount := 0
  492. done := false
  493. wg.Add(1)
  494. go func(basedir string) {
  495. defer func() {
  496. atomic.AddInt32(&mqlcount, dirvars.mqlcount)
  497. wg.Done()
  498. }()
  499. ch_ok := make(chan bool)
  500. go func() {
  501. for {
  502. select {
  503. case <-ch_parallel_count:
  504. if !done && !parallel {
  505. parallel = true
  506. // 加入并发控制队列
  507. if parallelcount > 0 {
  508. if parallelcount > parallel_queue.Size() {
  509. parallel_queue.Growth(parallelcount)
  510. }
  511. parallel_queue.Push(1)
  512. }
  513. parallel_chan <- true
  514. }
  515. case ok := <-ch_ok:
  516. ok_chan <- ok
  517. if parallel {
  518. if parallelcount > 0 {
  519. // 从并发控制队列中移除
  520. parallel_queue.Pop()
  521. }
  522. } else {
  523. done = true
  524. }
  525. return
  526. }
  527. }
  528. }()
  529. // logger.Info("dir", basedir, "第", fmt.Sprint(topvars.loop_i, ".", dirvars.loop_i), "次执行开始")
  530. files := dirfiles[basedir]
  531. ch_ok <- mt.RunDir(t, ctx,
  532. global,
  533. topvars,
  534. dirvars,
  535. basedir, files)
  536. // logger.Info("dir", basedir, "第", fmt.Sprint(topvars.loop_i, ".", dirvars.loop_i), "次执行结束")
  537. }(basedir)
  538. success := true
  539. select {
  540. case success = <-ok_chan: // 非并发,等待完成
  541. logger.Info("dir", basedir, "第", fmt.Sprint(topvars.loop_i, ".", dirvars.loop_i), "次顺序执行完成")
  542. case <-parallel_chan: // 并发,执行继续下一次
  543. logger.Info("dir", basedir, "第", fmt.Sprint(topvars.loop_i, ".", dirvars.loop_i), "次并发执行继续")
  544. }
  545. if !success {
  546. return false
  547. }
  548. }
  549. wg.Wait()
  550. mt.scopevars.RLock()
  551. loop_count := mt.scopevars.dir[basedir].loop_count
  552. mt.scopevars.RUnlock()
  553. if loop_count > 1 {
  554. ut := time.Since(st)
  555. logger.Info(fmt.Sprint("dir ", basedir, " loop ", loop_count, " times, run ", mqlcount, " mqls, usetime ", ut))
  556. }
  557. }
  558. logger.Info("完成第", topvars.loop_i, "次执行,共", topvars.mqlcount, "次 MQL 请求,耗时", time.Since(st))
  559. return true
  560. }
  561. func (mt *MQLTest) RunDir(t *testing.T, ctx context.Context,
  562. global *GlobalVars,
  563. topvars *CurrentVars,
  564. dirvars *CurrentVars,
  565. basedir string, files []string) bool {
  566. for _, filename := range files {
  567. ok := mt.RunFile(t, ctx, global, topvars, dirvars, basedir, filename)
  568. if !ok {
  569. return false
  570. }
  571. }
  572. return true
  573. }
  574. func (mt *MQLTest) RunFile(t *testing.T, ctx context.Context,
  575. global *GlobalVars,
  576. topvars *CurrentVars,
  577. dirvars *CurrentVars,
  578. basedir, filename string) bool {
  579. // 读取文件内容
  580. ffpath := filepath.Join(basedir, filename)
  581. bs, err := os.ReadFile(ffpath)
  582. if !assert.Nil(t, err, err) {
  583. return false
  584. }
  585. // mql语句切分
  586. mqgr := NewMQLGroupRequest()
  587. var multilines *MQLRequest
  588. mqs := spliter.NewMQLSpliter(bufio.NewReader(strings.NewReader(string(bs))))
  589. for {
  590. mql, fromline, toline, fromchar, tochar, hasnext, _ := mqs.NextMQL()
  591. if !hasnext {
  592. break
  593. }
  594. if multilines != nil {
  595. if strings.TrimSpace(mql) == "multilines end" {
  596. e := mqgr.Append(multilines)
  597. if !assert.Nil(t, e, e) {
  598. return false
  599. }
  600. multilines = nil
  601. } else if multilines.OriginQueryString == "" {
  602. multilines.OriginQueryString = mql
  603. multilines.Fromline = fromline
  604. multilines.Toline = toline
  605. multilines.Fromchar = fromchar
  606. multilines.Tochar = tochar
  607. } else {
  608. multilines.OriginQueryString += ";" + mql
  609. multilines.Toline = toline
  610. multilines.Tochar = tochar
  611. }
  612. } else if strings.TrimSpace(mql) == "multilines begin" {
  613. multilines = &MQLRequest{FilePath: ffpath}
  614. } else {
  615. mqr := &MQLRequest{OriginQueryString: mql, FilePath: ffpath, Fromline: fromline, Toline: toline, Fromchar: fromchar, Tochar: tochar}
  616. e := mqgr.Append(mqr)
  617. if !assert.Nil(t, e, e) {
  618. return false
  619. }
  620. }
  621. }
  622. // mqls := spliter.MQLSplit(string(bs))
  623. mt.scopevars.Lock()
  624. if mt.scopevars.file[ffpath] == nil {
  625. mt.scopevars.file[ffpath] = &Variables{
  626. vars: map[string]interface{}{},
  627. loop_count: 1,
  628. loop_from: 1,
  629. loop_step: 1}
  630. }
  631. mt.scopevars.Unlock()
  632. var wg sync.WaitGroup
  633. st := time.Now()
  634. loop_i := 0
  635. parallel_queue := pqc.NewQueue[any](0)
  636. mqlcount := int32(0)
  637. for {
  638. mt.scopevars.Lock()
  639. ok := loop_i < mt.scopevars.file[ffpath].loop_count
  640. mt.scopevars.Unlock()
  641. if !ok {
  642. break
  643. }
  644. loop_i++
  645. //
  646. ch_parallel_count := make(chan int)
  647. filevars := &CurrentVars{
  648. loop_i: loop_i,
  649. ch_parallel_count: ch_parallel_count,
  650. }
  651. //
  652. ok_chan := make(chan bool, 1)
  653. parallel_chan := make(chan bool, 1)
  654. parallel := false
  655. parallelcount := 0
  656. done := false
  657. wg.Add(1)
  658. go func() {
  659. defer func() {
  660. atomic.AddInt32(&mqlcount, filevars.mqlcount)
  661. wg.Done()
  662. }()
  663. ch_ok := make(chan bool)
  664. go func() {
  665. for {
  666. select {
  667. case <-ch_parallel_count:
  668. if !done && !parallel {
  669. parallel = true
  670. // 加入并发控制队列
  671. if parallelcount > 0 {
  672. if parallelcount > parallel_queue.Size() {
  673. parallel_queue.Growth(parallelcount)
  674. }
  675. parallel_queue.Push(1)
  676. }
  677. parallel_chan <- true
  678. }
  679. case ok := <-ch_ok:
  680. ok_chan <- ok
  681. if parallel {
  682. if parallelcount > 0 {
  683. // 从并发控制队列中移除
  684. parallel_queue.Pop()
  685. }
  686. } else {
  687. done = true
  688. }
  689. return
  690. }
  691. }
  692. }()
  693. // logger.Info("file", ffpath, "第", fmt.Sprint(topvars.loop_i, ".", dirvars.loop_i, ".", filevars.loop_i), "次执行开始")
  694. ch_ok <- mt.RunMQLGroup(t, ctx,
  695. global,
  696. topvars,
  697. dirvars,
  698. filevars,
  699. basedir, ffpath, mqgr)
  700. // logger.Info("file", ffpath, "第", fmt.Sprint(topvars.loop_i, ".", dirvars.loop_i, ".", filevars.loop_i), "次执行结束")
  701. }()
  702. success := true
  703. select {
  704. case success = <-ok_chan: // 非并发,等待完成
  705. logger.Info("file", ffpath, "第", fmt.Sprint(topvars.loop_i, ".", dirvars.loop_i, ".", filevars.loop_i), "次顺序执行完成")
  706. case <-parallel_chan: // 并发,执行继续下一次
  707. logger.Info("file", ffpath, "第", fmt.Sprint(topvars.loop_i, ".", dirvars.loop_i, ".", filevars.loop_i), "次并发执行继续")
  708. }
  709. if !success {
  710. return false
  711. }
  712. }
  713. wg.Wait()
  714. mt.scopevars.RLock()
  715. loop_count := mt.scopevars.file[ffpath].loop_count
  716. mt.scopevars.RUnlock()
  717. if loop_count > 1 {
  718. ut := time.Since(st)
  719. sn := fmt.Sprint(topvars.loop_i, ".", dirvars.loop_i)
  720. logger.Info(fmt.Sprint("file ", ffpath+"/"+sn, " loop ", loop_count, " times, run ", mqlcount, " mqls, usetime ", ut))
  721. }
  722. return true
  723. }
  724. func (mt *MQLTest) RunMQLGroup(t *testing.T, ctx context.Context,
  725. global *GlobalVars,
  726. topvars *CurrentVars,
  727. dirvars *CurrentVars,
  728. filevars *CurrentVars,
  729. basedir, ffpath string, mqgr *MQLGroupRequest) (pass bool) {
  730. pass = true
  731. var wg sync.WaitGroup
  732. for _, mqs := range mqgr.mqrs {
  733. wg.Add(1)
  734. go func(mqs []*MQLRequest) {
  735. defer wg.Done()
  736. if len(mqs) == 0 {
  737. return
  738. }
  739. if mqs[0].StaticActions.ForkName != nil {
  740. forkname := *mqs[0].StaticActions.ForkName
  741. global.Lock()
  742. wg := global.wg_wait_fork_routine[forkname]
  743. if wg == nil {
  744. wg = &sync.WaitGroup{}
  745. global.wg_wait_fork_routine[forkname] = wg
  746. }
  747. global.Unlock()
  748. wg.Add(1)
  749. defer wg.Done()
  750. }
  751. ok := mt.RunMQLs(t, ctx, global, topvars, dirvars, filevars, basedir, ffpath, mqs)
  752. if !ok {
  753. pass = false
  754. }
  755. }(mqs)
  756. }
  757. wg.Wait()
  758. return
  759. }
  760. func (mt *MQLTest) RunMQLs(t *testing.T, ctx context.Context,
  761. global *GlobalVars,
  762. topvars *CurrentVars,
  763. dirvars *CurrentVars,
  764. filevars *CurrentVars,
  765. basedir, ffpath string, mqrs []*MQLRequest) bool {
  766. for _, mqr := range mqrs {
  767. mqlkey := mqr.Key
  768. mqlstr := mqr.OriginQueryString
  769. if mqlstr == "" {
  770. continue
  771. }
  772. staticactions := mqr.StaticActions
  773. // 设置执行过程中的控制参数
  774. mt.InitScopeVars(basedir, ffpath, mqlkey, staticactions)
  775. ch_test_run_one_mql_result := make(chan bool)
  776. go func() {
  777. mqrinst := fmt.Sprint(mqlkey, "/", topvars.loop_i, ".", dirvars.loop_i, ".", filevars.loop_i)
  778. global.Lock()
  779. mqrdone := global.ch_wait_mql_done[mqrinst]
  780. if mqrdone == nil {
  781. mqrdone = make(chan bool)
  782. global.ch_wait_mql_done[mqrinst] = mqrdone
  783. }
  784. var waitmqrdone chan bool
  785. if mqr.WaitMQLRequest != nil {
  786. waitmqrkey := mqr.WaitMQLRequest.Key
  787. waitmqrinst := fmt.Sprint(waitmqrkey, "/", topvars.loop_i, ".", dirvars.loop_i, ".", filevars.loop_i)
  788. waitmqrdone = global.ch_wait_mql_done[waitmqrinst]
  789. if waitmqrdone == nil {
  790. waitmqrdone = make(chan bool)
  791. global.ch_wait_mql_done[waitmqrinst] = waitmqrdone
  792. }
  793. }
  794. global.Unlock()
  795. var ret bool
  796. defer func() { mqrdone <- ret }()
  797. if waitmqrdone != nil {
  798. v := <-waitmqrdone
  799. waitmqrdone <- v
  800. if !v {
  801. // 依赖MQR失败
  802. ch_test_run_one_mql_result <- false
  803. return
  804. }
  805. }
  806. ret = mt.RunMQR(t, ctx, global, topvars, dirvars, filevars, basedir, ffpath, mqr)
  807. ch_test_run_one_mql_result <- ret
  808. }()
  809. ret := <-ch_test_run_one_mql_result
  810. if !ret {
  811. return ret
  812. }
  813. // continue
  814. }
  815. return true
  816. }
  817. func (mt *MQLTest) RunMQR(t *testing.T, ctx context.Context,
  818. global *GlobalVars,
  819. topvars *CurrentVars,
  820. dirvars *CurrentVars,
  821. filevars *CurrentVars,
  822. basedir, ffpath string, mqr *MQLRequest) bool {
  823. mqlkey := mqr.Key
  824. staticactionexprs := mqr.StaticActionExprs
  825. staticactions := mqr.StaticActions
  826. return t.Run(mqlkey, func(t *testing.T) {
  827. var wg sync.WaitGroup
  828. st := time.Now()
  829. loop_i := 0
  830. parallel_queue := pqc.NewQueue[any](0)
  831. mqlcount := int32(0)
  832. for {
  833. mt.scopevars.Lock()
  834. ok := loop_i < mt.scopevars.mql[mqlkey].loop_count
  835. mt.scopevars.Unlock()
  836. if !ok {
  837. break
  838. }
  839. loop_i++
  840. //
  841. ch_parallel_count := make(chan int)
  842. mqlvars := &CurrentVars{
  843. loop_i: loop_i,
  844. ch_parallel_count: ch_parallel_count,
  845. }
  846. // 运行实例
  847. mqlsn := fmt.Sprint(mqlkey, "/", topvars.loop_i, ".", dirvars.loop_i, ".", filevars.loop_i, ".", mqlvars.loop_i)
  848. mt.scopevars.Lock()
  849. if mt.scopevars.mql[mqlsn] == nil {
  850. mt.scopevars.mql[mqlsn] = &Variables{
  851. vars: map[string]interface{}{},
  852. loop_count: 1,
  853. loop_from: 1,
  854. loop_step: 1}
  855. }
  856. mt.scopevars.Unlock()
  857. //
  858. mt.scopevars.Lock()
  859. top_loopi := mt.scopevars.top.loop_from + (topvars.loop_i-1)*mt.scopevars.top.loop_step
  860. mt.scopevars.top.vars["topi"] = top_loopi
  861. dir_loopi := mt.scopevars.dir[basedir].loop_from + (dirvars.loop_i-1)*mt.scopevars.dir[basedir].loop_step
  862. mt.scopevars.dir[basedir].vars["diri"] = dir_loopi
  863. mt.scopevars.dir[basedir].vars["topi"] = top_loopi
  864. file_loopi := mt.scopevars.file[ffpath].loop_from + (filevars.loop_i-1)*mt.scopevars.file[ffpath].loop_step
  865. mt.scopevars.file[ffpath].vars["filei"] = file_loopi
  866. mt.scopevars.file[ffpath].vars["diri"] = dir_loopi
  867. mt.scopevars.file[ffpath].vars["topi"] = top_loopi
  868. mql_loopi := mt.scopevars.mql[mqlkey].loop_from + (mqlvars.loop_i-1)*mt.scopevars.mql[mqlkey].loop_step
  869. mt.scopevars.mql[mqlkey].vars["mqli"] = mql_loopi
  870. mt.scopevars.mql[mqlkey].vars["filei"] = file_loopi
  871. mt.scopevars.mql[mqlkey].vars["diri"] = dir_loopi
  872. mt.scopevars.mql[mqlkey].vars["topi"] = top_loopi
  873. //
  874. mt.scopevars.mql[mqlsn].vars["mqli"] = mql_loopi
  875. mt.scopevars.mql[mqlsn].vars["filei"] = file_loopi
  876. mt.scopevars.mql[mqlsn].vars["diri"] = dir_loopi
  877. mt.scopevars.mql[mqlsn].vars["topi"] = top_loopi
  878. mt.scopevars.Unlock()
  879. mt.BeforeRunAction(basedir, ffpath, mqlkey, mqlsn, staticactions)
  880. formatedmqlstr := mqr.FormatedQueryString
  881. mql := mt.ReplaceLoopSN(formatedmqlstr,
  882. global, topvars, dirvars, filevars, mqlvars,
  883. top_loopi, dir_loopi, file_loopi, mql_loopi,
  884. basedir, ffpath, mqlkey, mqlsn,
  885. )
  886. mqlreplace := rereplace_nbytes.FindAllStringSubmatch(mql, -1)
  887. for _, mqr := range mqlreplace {
  888. if len(mqr) == 2 {
  889. bs := make([]byte, cast.ToInt(mqr[1]))
  890. for i := 0; i < len(bs); i++ {
  891. bs[i] = byte(32 + rand.Intn(91))
  892. }
  893. s := string(bs)
  894. s = strings.ReplaceAll(s, ")", string([]byte{123}))
  895. s = strings.ReplaceAll(s, "'", string([]byte{124}))
  896. s = strings.ReplaceAll(s, "\"", string([]byte{125}))
  897. s = strings.ReplaceAll(s, "\\", string([]byte{126}))
  898. mql = strings.Replace(mql, mqr[0], s, 1)
  899. }
  900. }
  901. for i, sat := range staticactionexprs {
  902. mql = strings.Replace(mql, "["+strconv.Itoa(i)+"]", sat.SourceText, 1)
  903. }
  904. mql = strings.ReplaceAll(mql, "[[]", "[")
  905. mqri := &MQLRequestInstance{
  906. MQLRequest: mqr,
  907. PreparedQueryString: mql,
  908. }
  909. //
  910. ok_chan := make(chan error, 1)
  911. parallel_chan := make(chan bool, 1)
  912. parallel := false
  913. parallelcount := 0
  914. done := false
  915. wg.Add(1)
  916. go func(mqlvars *CurrentVars) {
  917. defer func() {
  918. atomic.AddInt32(&mqlcount, mqlvars.mqlcount)
  919. wg.Done()
  920. }()
  921. ch_ok := make(chan error)
  922. go func() {
  923. for {
  924. select {
  925. case parallelcount = <-ch_parallel_count:
  926. if !done && !parallel {
  927. parallel = true
  928. // 加入并发控制队列
  929. if parallelcount > 0 {
  930. if parallelcount > parallel_queue.Size() {
  931. parallel_queue.Growth(parallelcount)
  932. }
  933. parallel_queue.Push(1)
  934. }
  935. parallel_chan <- true
  936. }
  937. case ok := <-ch_ok:
  938. ok_chan <- ok
  939. if parallel {
  940. if parallelcount > 0 {
  941. // 从并发控制队列中移除
  942. parallel_queue.Pop()
  943. }
  944. } else {
  945. done = true
  946. }
  947. return
  948. }
  949. }
  950. }()
  951. nstaticactionexprs := map[int]*Action{}
  952. for i, sat := range staticactionexprs {
  953. nstaticactionexprs[i] = sat
  954. }
  955. // logger.Info(mqlkey, "第", fmt.Sprint(all_loop_i, ".", dir_loop_i, ".", file_loop_i, ".", curval.mql_i), "次执行开始")
  956. ch_ok <- mt.RunMQL(t, ctx,
  957. global,
  958. topvars,
  959. dirvars,
  960. filevars,
  961. mqlvars,
  962. basedir, ffpath, mqlkey, mqlsn, mqri, staticactions, nstaticactionexprs)
  963. // logger.Info(mqlkey, "第", fmt.Sprint(all_loop_i, ".", dir_loop_i, ".", file_loop_i, ".", curval.mql_i), "次执行结束")
  964. }(mqlvars)
  965. var err error
  966. select {
  967. case err = <-ok_chan: // 非并发,等待完成
  968. // logger.Info(mqlkey, "第", fmt.Sprint(all_loop_i, ".", dir_loop_i, ".", file_loop_i, ".", curval.mql_i), "次顺序执行完成")
  969. case <-parallel_chan: // 并发,执行继续下一次
  970. // logger.Info(mqlkey, "第", fmt.Sprint(all_loop_i, ".", dir_loop_i, ".", file_loop_i, ".", curval.mql_i), "次并发执行继续")
  971. }
  972. if err != nil {
  973. // logger.Error(err)
  974. break
  975. }
  976. }
  977. wg.Wait()
  978. mt.scopevars.RLock()
  979. loop_count := mt.scopevars.mql[mqlkey].loop_count
  980. mt.scopevars.RUnlock()
  981. if loop_count > 1 {
  982. ut := time.Since(st)
  983. sn := fmt.Sprint(topvars.loop_i, ".", dirvars.loop_i, ".", filevars.loop_i)
  984. as := ""
  985. if topvars.sleeptime > 0 {
  986. as = fmt.Sprint(", sleep ", topvars.sleeptime)
  987. }
  988. logger.Info(fmt.Sprint("mql ", mqlkey+"/"+sn, " loop ", loop_i, " times, usetime ", ut, as))
  989. }
  990. })
  991. }
  992. func (mt *MQLTest) getValue(basedir, ffpath, mqlkey, mqlsn string,
  993. staticactions *StaticActions, a any) (ak string, va any) {
  994. switch av := a.(type) {
  995. case *Action:
  996. switch av.Name {
  997. case "<EQ>":
  998. if len(av.Args) >= 2 {
  999. _, x := mt.getValue(basedir, ffpath, mqlkey, mqlsn, staticactions, av.Args[0])
  1000. _, y := mt.getValue(basedir, ffpath, mqlkey, mqlsn, staticactions, av.Args[1])
  1001. if cast.ToString(x) == cast.ToString(y) {
  1002. return "", true
  1003. }
  1004. }
  1005. return "", false
  1006. }
  1007. case *qstru.Expr:
  1008. ak = av.VarName
  1009. if ak == "now" {
  1010. return "", time.Now()
  1011. }
  1012. mt.scopevars.Lock()
  1013. switch staticactions.Scope {
  1014. case "top":
  1015. va = mt.scopevars.top.vars[ak]
  1016. case "dir":
  1017. va = mt.scopevars.dir[basedir].vars[ak]
  1018. case "file":
  1019. va = mt.scopevars.file[ffpath].vars[ak]
  1020. default:
  1021. var has bool
  1022. va, has = mt.scopevars.mql[mqlsn].vars[ak]
  1023. if !has {
  1024. va = mt.scopevars.mql[mqlkey].vars[ak]
  1025. }
  1026. }
  1027. mt.scopevars.Unlock()
  1028. case string:
  1029. va = av
  1030. for _, tf := range time_layouts {
  1031. t, e := time.Parse(tf, av)
  1032. if e == nil {
  1033. va = t
  1034. break
  1035. }
  1036. }
  1037. default:
  1038. va = a
  1039. }
  1040. return
  1041. }
  1042. func (mt *MQLTest) setValue(basedir, ffpath, mqlkey, mqlsn string,
  1043. staticactions *StaticActions, ak string, va any) {
  1044. mt.scopevars.Lock()
  1045. switch staticactions.Scope {
  1046. case "top":
  1047. mt.scopevars.top.vars[ak] = va
  1048. case "dir":
  1049. mt.scopevars.dir[basedir].vars[ak] = va
  1050. case "file":
  1051. mt.scopevars.file[ffpath].vars[ak] = va
  1052. default:
  1053. _, has := mt.scopevars.mql[mqlsn].vars[ak]
  1054. if has {
  1055. mt.scopevars.mql[mqlsn].vars[ak] = va
  1056. } else {
  1057. mt.scopevars.mql[mqlkey].vars[ak] = va
  1058. }
  1059. }
  1060. mt.scopevars.Unlock()
  1061. }
  1062. func (mt *MQLTest) BeforeRunAction(basedir, ffpath, mqlkey, mqlsn string,
  1063. staticactions *StaticActions,
  1064. ) {
  1065. mt.runAction(basedir, ffpath, mqlkey, mqlsn, staticactions, staticactions.BeforeRunActions...)
  1066. }
  1067. func (mt *MQLTest) runAction(basedir, ffpath, mqlkey, mqlsn string,
  1068. staticactions *StaticActions, actions ...*Action,
  1069. ) {
  1070. for _, act := range actions {
  1071. switch act.Name {
  1072. case "set":
  1073. var a, b any
  1074. var ak string
  1075. if len(act.Args) > 1 {
  1076. a = act.Args[0]
  1077. b = act.Args[1]
  1078. }
  1079. ak, _ = mt.getValue(basedir, ffpath, mqlkey, mqlsn, staticactions, a)
  1080. _, vb := mt.getValue(basedir, ffpath, mqlkey, mqlsn, staticactions, b)
  1081. mt.setValue(basedir, ffpath, mqlkey, mqlsn, staticactions, ak, vb)
  1082. case "add":
  1083. var a, b, va, vb any
  1084. var ak string
  1085. if len(act.Args) > 1 {
  1086. a = act.Args[0]
  1087. b = act.Args[1]
  1088. }
  1089. ak, va = mt.getValue(basedir, ffpath, mqlkey, mqlsn, staticactions, a)
  1090. _, vb = mt.getValue(basedir, ffpath, mqlkey, mqlsn, staticactions, b)
  1091. switch v := va.(type) {
  1092. case time.Time:
  1093. unit := "second"
  1094. if len(act.Args) > 2 {
  1095. unit = cast.ToString(act.Args[2])
  1096. }
  1097. vb := cast.ToInt(vb)
  1098. d := time.Duration(0)
  1099. switch unit {
  1100. case "second", "seconds", "s", "秒":
  1101. d = time.Duration(vb) * time.Second
  1102. case "minute", "minutes", "m", "分":
  1103. d = time.Duration(vb) * time.Minute
  1104. case "hour", "hours", "h", "时":
  1105. d = time.Duration(vb) * time.Hour
  1106. }
  1107. v = v.Add(d)
  1108. mt.setValue(basedir, ffpath, mqlkey, mqlsn, staticactions, ak, v)
  1109. }
  1110. case "mod":
  1111. var a, b, va, vb any
  1112. var ak string
  1113. if len(act.Args) > 1 {
  1114. a = act.Args[0]
  1115. b = act.Args[1]
  1116. }
  1117. ak, va = mt.getValue(basedir, ffpath, mqlkey, mqlsn, staticactions, a)
  1118. _, vb = mt.getValue(basedir, ffpath, mqlkey, mqlsn, staticactions, b)
  1119. av := cast.ToInt(va)
  1120. bv := cast.ToInt(vb)
  1121. v := av % bv
  1122. mt.setValue(basedir, ffpath, mqlkey, mqlsn, staticactions, ak, v)
  1123. case "case":
  1124. var a, b, va any
  1125. if len(act.Args) > 1 {
  1126. a = act.Args[0]
  1127. b = act.Args[1]
  1128. }
  1129. _, va = mt.getValue(basedir, ffpath, mqlkey, mqlsn, staticactions, a)
  1130. if cast.ToBool(va) {
  1131. switch vb := b.(type) {
  1132. case *Action:
  1133. mt.runAction(basedir, ffpath, mqlkey, mqlsn, staticactions, vb)
  1134. }
  1135. }
  1136. }
  1137. }
  1138. }
  1139. func (mt *MQLTest) InitScopeVars(basedir, ffpath, mqlkey string,
  1140. staticactions *StaticActions,
  1141. ) {
  1142. mt.scopevars.Lock()
  1143. if mt.scopevars.mql[mqlkey] == nil {
  1144. mt.scopevars.mql[mqlkey] = &Variables{
  1145. vars: map[string]interface{}{},
  1146. loop_count: 1,
  1147. loop_from: 1,
  1148. loop_step: 1}
  1149. }
  1150. mt.scopevars.Unlock()
  1151. for k, v := range staticactions.Variables {
  1152. mt.scopevars.Lock()
  1153. switch staticactions.Scope {
  1154. case "top":
  1155. mt.scopevars.top.vars[k] = v
  1156. case "dir":
  1157. mt.scopevars.dir[basedir].vars[k] = v
  1158. case "file":
  1159. mt.scopevars.file[ffpath].vars[k] = v
  1160. default:
  1161. mt.scopevars.mql[mqlkey].vars[k] = v
  1162. }
  1163. mt.scopevars.Unlock()
  1164. }
  1165. if staticactions.Timeout != nil {
  1166. mt.scopevars.Lock()
  1167. switch staticactions.Scope {
  1168. case "top":
  1169. mt.scopevars.top.timeout = *staticactions.Timeout
  1170. case "dir":
  1171. mt.scopevars.dir[basedir].timeout = *staticactions.Timeout
  1172. case "file":
  1173. mt.scopevars.file[ffpath].timeout = *staticactions.Timeout
  1174. default:
  1175. mt.scopevars.mql[mqlkey].timeout = *staticactions.Timeout
  1176. }
  1177. mt.scopevars.Unlock()
  1178. }
  1179. if staticactions.Qmeta != nil {
  1180. mt.scopevars.Lock()
  1181. switch staticactions.Scope {
  1182. case "top":
  1183. mt.scopevars.top.qmeta = staticactions.Qmeta
  1184. case "dir":
  1185. mt.scopevars.dir[basedir].qmeta = staticactions.Qmeta
  1186. case "file":
  1187. mt.scopevars.file[ffpath].qmeta = staticactions.Qmeta
  1188. default:
  1189. mt.scopevars.mql[mqlkey].qmeta = staticactions.Qmeta
  1190. }
  1191. mt.scopevars.Unlock()
  1192. }
  1193. if staticactions.LoopCount != nil {
  1194. mt.scopevars.Lock()
  1195. switch staticactions.Scope {
  1196. case "top":
  1197. mt.scopevars.top.loop_count = *staticactions.LoopCount
  1198. case "dir":
  1199. mt.scopevars.dir[basedir].loop_count = *staticactions.LoopCount
  1200. case "file":
  1201. mt.scopevars.file[ffpath].loop_count = *staticactions.LoopCount
  1202. default:
  1203. mt.scopevars.mql[mqlkey].loop_count = *staticactions.LoopCount
  1204. }
  1205. mt.scopevars.Unlock()
  1206. }
  1207. if staticactions.LoopFrom != nil {
  1208. mt.scopevars.Lock()
  1209. switch staticactions.Scope {
  1210. case "top":
  1211. mt.scopevars.top.loop_from = *staticactions.LoopFrom
  1212. case "dir":
  1213. mt.scopevars.dir[basedir].loop_from = *staticactions.LoopFrom
  1214. case "file":
  1215. mt.scopevars.file[ffpath].loop_from = *staticactions.LoopFrom
  1216. default:
  1217. mt.scopevars.mql[mqlkey].loop_from = *staticactions.LoopFrom
  1218. }
  1219. mt.scopevars.Unlock()
  1220. }
  1221. if staticactions.LoopStep != nil {
  1222. mt.scopevars.Lock()
  1223. switch staticactions.Scope {
  1224. case "top":
  1225. mt.scopevars.top.loop_step = *staticactions.LoopStep
  1226. case "dir":
  1227. mt.scopevars.dir[basedir].loop_step = *staticactions.LoopStep
  1228. case "file":
  1229. mt.scopevars.file[ffpath].loop_step = *staticactions.LoopStep
  1230. default:
  1231. mt.scopevars.mql[mqlkey].loop_step = *staticactions.LoopStep
  1232. }
  1233. mt.scopevars.Unlock()
  1234. }
  1235. }
  1236. func (mt *MQLTest) RunMQL(t *testing.T, ctx context.Context,
  1237. global *GlobalVars,
  1238. topvars *CurrentVars,
  1239. dirvars *CurrentVars,
  1240. filevars *CurrentVars,
  1241. mqlvars *CurrentVars,
  1242. basedir, ffpath, mqlkey, mqlsn string, mqri *MQLRequestInstance, staticactions *StaticActions, staticactionexprs map[int]*Action) error {
  1243. mqlstr := mqri.PreparedQueryString
  1244. if staticactions.WaitName != nil {
  1245. global.Lock()
  1246. wgs := []*sync.WaitGroup{}
  1247. if *staticactions.WaitName == "" {
  1248. for _, wg := range global.wg_wait_fork_routine {
  1249. wgs = append(wgs, wg)
  1250. }
  1251. } else {
  1252. wg := global.wg_wait_fork_routine[*staticactions.WaitName]
  1253. if wg != nil {
  1254. wgs = append(wgs, wg)
  1255. }
  1256. }
  1257. global.Unlock()
  1258. for _, wg := range wgs {
  1259. wg.Wait()
  1260. }
  1261. }
  1262. if staticactions.ParallelCount != nil {
  1263. mt.scopevars.Lock()
  1264. switch staticactions.Scope {
  1265. case "top":
  1266. topvars.ch_parallel_count <- *staticactions.ParallelCount
  1267. case "dir":
  1268. dirvars.ch_parallel_count <- *staticactions.ParallelCount
  1269. case "file":
  1270. filevars.ch_parallel_count <- *staticactions.ParallelCount
  1271. default:
  1272. mqlvars.ch_parallel_count <- *staticactions.ParallelCount
  1273. }
  1274. mt.scopevars.Unlock()
  1275. }
  1276. // 重新获取修正后的动作
  1277. actionexprs, e := getActionExprs(mqlstr, staticactionexprs)
  1278. if !assert.Nil(t, e, e) {
  1279. return e
  1280. }
  1281. dynamicactions := actionexprs.DynamicActions()
  1282. if len(dynamicactions.SubscribeArgs) > 0 {
  1283. subscribe(dynamicactions.SubscribeArgs...)
  1284. }
  1285. if len(dynamicactions.UnsubscribeArgs) > 0 {
  1286. unsubscribe(dynamicactions.UnsubscribeArgs...)
  1287. }
  1288. values := []interface{}{}
  1289. if len(dynamicactions.Params) > 0 {
  1290. err := json.Unmarshal([]byte(dynamicactions.Params), &values)
  1291. if err != nil {
  1292. assert.Nil(t, fmt.Sprint("params参数只支持JSON Array,", dynamicactions.Params, mqlstr), err)
  1293. return err
  1294. }
  1295. }
  1296. x := atomic.AddInt32(&global.mqlcount, 1)
  1297. atomic.AddInt32(&topvars.mqlcount, 1)
  1298. atomic.AddInt32(&dirvars.mqlcount, 1)
  1299. atomic.AddInt32(&filevars.mqlcount, 1)
  1300. atomic.AddInt32(&mqlvars.mqlcount, 1)
  1301. err := mt.RunMQLTryDo(t, ctx,
  1302. global,
  1303. topvars,
  1304. dirvars,
  1305. filevars,
  1306. mqlvars,
  1307. basedir, ffpath, mqlkey, mqlsn+"("+strconv.Itoa(int(x))+")", mqri, values, staticactions, actionexprs)
  1308. if err != nil {
  1309. // 执行过程有错,停止继续执行
  1310. return err
  1311. }
  1312. if staticactions.SleepTime != nil {
  1313. global.sleeptime += *staticactions.SleepTime
  1314. topvars.sleeptime += *staticactions.SleepTime
  1315. dirvars.sleeptime += *staticactions.SleepTime
  1316. filevars.sleeptime += *staticactions.SleepTime
  1317. mqlvars.sleeptime += *staticactions.SleepTime
  1318. time.Sleep(*staticactions.SleepTime)
  1319. }
  1320. return nil
  1321. }