mql_run.go 42 KB

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