mql_run.go 42 KB

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