mql_run.go 42 KB

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