main.go 9.3 KB
Newer Older
X
Xin.Zh 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
 *
 * This program is free software: you can use, redistribute, and/or modify
 * it under the terms of the GNU Affero General Public License, version 3
 * or later ("AGPL"), as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

B
Bomin Zhang 已提交
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
package main

import (
	"database/sql"
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"math/rand"
	"os"
	"os/signal"
	"strings"
	"sync"
	"sync/atomic"
	"time"

	_ "github.com/taosdata/driver-go/taosSql"
)

type argument struct {
	Type string        `json:"type"`
	Min  int           `json:"min"`
	Max  int           `json:"max"`
	List []interface{} `json:"list, omitempty"`
}

B
Bomin Zhang 已提交
42
type testCase struct {
B
Bomin Zhang 已提交
43 44
	isQuery bool       `json:"-"`
	numArgs int        `json:"-"`
B
Bomin Zhang 已提交
45
	Weight  int        `json:"weight"`
46
	SQL     string     `json:"sql"`
B
Bomin Zhang 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
	Args    []argument `json:"args"`
}

func (arg *argument) check() (int, error) {
	if arg.Type == "list" {
		if len(arg.List) == 0 {
			return 0, errors.New("list cannot be empty")
		}
		return 1, nil
	}

	if arg.Max < arg.Min {
		return 0, errors.New("invalid min/max value")
	}

	if arg.Type == "string" {
		if arg.Min < 0 {
			return 0, errors.New("negative string length")
		}
	}

	if arg.Type == "int" && arg.Min == 0 && arg.Max == 0 {
		arg.Max = arg.Min + 100
	}

	if arg.Type == "range" {
		return 2, nil
	}

	return 1, nil
}

func (arg *argument) generate(args []interface{}) []interface{} {
	const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

	switch arg.Type {
	case "bool":
		if rand.Intn(2) == 1 {
			args = append(args, true)
		} else {
			args = append(args, false)
		}

	case "int":
		v := rand.Intn(arg.Max-arg.Min+1) + arg.Min
		args = append(args, v)

	case "range":
		v := rand.Intn(arg.Max-arg.Min) + arg.Min
		args = append(args, v)
		v = rand.Intn(arg.Max-v+1) + v
		args = append(args, v)

	case "string":
		l := rand.Intn(arg.Max-arg.Min+1) + arg.Min
		sb := strings.Builder{}
		for i := 0; i < l; i++ {
			sb.WriteByte(chars[rand.Intn(len(chars))])
		}
		args = append(args, sb.String())

	case "list":
		v := arg.List[rand.Intn(len(arg.List))]
		args = append(args, v)
	}

	return args
}

B
Bomin Zhang 已提交
116 117 118 119 120
func (tc *testCase) buildSql() string {
	args := make([]interface{}, 0, tc.numArgs)
	for i := 0; i < len(tc.Args); i++ {
		args = tc.Args[i].generate(args)
	}
121
	return fmt.Sprintf(tc.SQL, args...)
B
Bomin Zhang 已提交
122 123
}

B
Bomin Zhang 已提交
124 125 126 127 128 129 130 131
type statitics struct {
	succeeded         int64
	failed            int64
	succeededDuration int64
	failedDuration    int64
}

var (
B
Bomin Zhang 已提交
132 133 134 135 136 137 138
	host     string
	port     uint
	database string
	user     string
	password string
	fetch    bool

B
Bomin Zhang 已提交
139 140
	chLog       chan string
	wgLog       sync.WaitGroup
B
Bomin Zhang 已提交
141 142
	startAt     time.Time
	shouldStop  int64
B
Bomin Zhang 已提交
143
	wgTest      sync.WaitGroup
B
Bomin Zhang 已提交
144 145 146
	stat        statitics
	totalWeight int
	cases       []testCase
B
Bomin Zhang 已提交
147 148
)

149 150
func loadTestCaseFromFile(file *os.File) error {
	if e := json.NewDecoder(file).Decode(&cases); e != nil {
B
Bomin Zhang 已提交
151 152 153
		return e
	}

154 155
	if len(cases) == 0 {
		return fmt.Errorf("no test case loaded.")
B
Bomin Zhang 已提交
156 157
	}

B
Bomin Zhang 已提交
158 159
	for i := 0; i < len(cases); i++ {
		c := &cases[i]
160 161
		c.SQL = strings.TrimSpace(c.SQL)
		c.isQuery = strings.ToLower(c.SQL[:6]) == "select"
B
Bomin Zhang 已提交
162 163 164 165
		if c.Weight < 0 {
			return fmt.Errorf("test %d: negative weight", i)
		}
		totalWeight += c.Weight
B
Bomin Zhang 已提交
166

B
Bomin Zhang 已提交
167 168
		for j := 0; j < len(c.Args); j++ {
			arg := &c.Args[j]
B
Bomin Zhang 已提交
169 170 171
			arg.Type = strings.ToLower(arg.Type)
			n, e := arg.check()
			if e != nil {
B
Bomin Zhang 已提交
172
				return fmt.Errorf("test case %d argument %d: %s", i, j, e.Error())
B
Bomin Zhang 已提交
173
			}
B
Bomin Zhang 已提交
174 175 176 177 178 179 180
			c.numArgs += n
		}
	}

	if totalWeight == 0 {
		for i := 0; i < len(cases); i++ {
			cases[i].Weight = 1
B
Bomin Zhang 已提交
181
		}
B
Bomin Zhang 已提交
182
		totalWeight = len(cases)
B
Bomin Zhang 已提交
183 184 185 186 187
	}

	return nil
}

188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
func loadTestCase(pathOrSQL string) error {
	if f, e := os.Open(pathOrSQL); e == nil {
		defer f.Close()
		return loadTestCaseFromFile(f)
	}

	pathOrSQL = strings.TrimSpace(pathOrSQL)
	if strings.ToLower(pathOrSQL[:6]) != "select" {
		return fmt.Errorf("'%s' is not a valid file or SQL statement", pathOrSQL)
	}

	cases = append(cases, testCase{
		isQuery: true,
		Weight:  1,
		numArgs: 0,
		SQL:     pathOrSQL,
	})
	totalWeight = 1

	return nil
}

B
Bomin Zhang 已提交
210 211 212 213 214 215 216 217 218
func selectTestCase() *testCase {
	sum, target := 0, rand.Intn(totalWeight)
	var c *testCase
	for i := 0; i < len(cases); i++ {
		c = &cases[i]
		sum += c.Weight
		if sum > target {
			break
		}
B
Bomin Zhang 已提交
219
	}
B
Bomin Zhang 已提交
220
	return c
B
Bomin Zhang 已提交
221 222 223
}

func runTest() {
B
Bomin Zhang 已提交
224
	defer wgTest.Done()
B
Bomin Zhang 已提交
225
	db, e := sql.Open("taosSql", fmt.Sprintf("%s:%s@tcp(%s:%v)/%s", user, password, host, port, database))
B
Bomin Zhang 已提交
226 227 228 229 230 231 232
	if e != nil {
		fmt.Printf("failed to connect to database: %s\n", e.Error())
		return
	}
	defer db.Close()

	for atomic.LoadInt64(&shouldStop) == 0 {
B
Bomin Zhang 已提交
233 234
		c := selectTestCase()
		str := c.buildSql()
B
Bomin Zhang 已提交
235

B
Bomin Zhang 已提交
236 237
		start := time.Now()
		if c.isQuery {
B
Bomin Zhang 已提交
238 239 240 241 242 243 244 245 246 247 248 249
			var rows *sql.Rows
			if rows, e = db.Query(str); rows != nil {
				if fetch {
					for rows.Next() {
					}
				}
				rows.Close()
			}
		} else {
			_, e = db.Exec(str)
		}
		duration := time.Now().Sub(start).Microseconds()
B
Bomin Zhang 已提交
250

B
Bomin Zhang 已提交
251
		if e != nil {
B
Bomin Zhang 已提交
252 253 254
			if chLog != nil {
				chLog <- str + ": " + e.Error()
			}
B
Bomin Zhang 已提交
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
			atomic.AddInt64(&stat.failed, 1)
			atomic.AddInt64(&stat.failedDuration, duration)
		} else {
			atomic.AddInt64(&stat.succeeded, 1)
			atomic.AddInt64(&stat.succeededDuration, duration)
		}
	}
}

func getStatPrinter() func(tm time.Time) {
	var last statitics
	lastPrintAt := startAt

	return func(tm time.Time) {
		var current statitics

		current.succeeded = atomic.LoadInt64(&stat.succeeded)
		current.failed = atomic.LoadInt64(&stat.failed)
		current.succeededDuration = atomic.LoadInt64(&stat.succeededDuration)
		current.failedDuration = atomic.LoadInt64(&stat.failedDuration)

		seconds := int64(tm.Sub(startAt).Seconds())
B
Bomin Zhang 已提交
277
		format := "\033[47;30m %02v:%02v:%02v | TOTAL REQ | TOTAL TIME(us) | TOTAL AVG(us) | REQUEST |  TIME(us)  |  AVERAGE(us)  |\033[0m\n"
B
Bomin Zhang 已提交
278 279 280 281 282 283 284 285 286 287 288 289 290
		fmt.Printf(format, seconds/3600, seconds%3600/60, seconds%60)

		tr := current.succeeded + current.failed
		td := current.succeededDuration + current.failedDuration
		r := tr - last.succeeded - last.failed
		d := td - last.succeededDuration - last.failedDuration
		ta, a := 0.0, 0.0
		if tr > 0 {
			ta = float64(td) / float64(tr)
		}
		if r > 0 {
			a = float64(d) / float64(r)
		}
B
Bomin Zhang 已提交
291
		format = "    TOTAL | %9v | %14v | %13.2f | %7v | %10v | % 13.2f |\n"
B
Bomin Zhang 已提交
292 293 294 295 296 297 298 299 300 301 302 303 304
		fmt.Printf(format, tr, td, ta, r, d, a)

		tr = current.succeeded
		td = current.succeededDuration
		r = tr - last.succeeded
		d = td - last.succeededDuration
		ta, a = 0.0, 0.0
		if tr > 0 {
			ta = float64(td) / float64(tr)
		}
		if r > 0 {
			a = float64(d) / float64(r)
		}
B
Bomin Zhang 已提交
305
		format = "  SUCCESS | \033[32m%9v\033[0m | \033[32m%14v\033[0m | \033[32m%13.2f\033[0m | \033[32m%7v\033[0m | \033[32m%10v\033[0m | \033[32m%13.2f\033[0m |\n"
B
Bomin Zhang 已提交
306 307 308 309 310 311 312 313 314 315 316 317 318
		fmt.Printf(format, tr, td, ta, r, d, a)

		tr = current.failed
		td = current.failedDuration
		r = tr - last.failed
		d = td - last.failedDuration
		ta, a = 0.0, 0.0
		if tr > 0 {
			ta = float64(td) / float64(tr)
		}
		if r > 0 {
			a = float64(d) / float64(r)
		}
B
Bomin Zhang 已提交
319
		format = "     FAIL | \033[31m%9v\033[0m | \033[31m%14v\033[0m | \033[31m%13.2f\033[0m | \033[31m%7v\033[0m | \033[31m%10v\033[0m | \033[31m%13.2f\033[0m |\n"
B
Bomin Zhang 已提交
320 321 322 323 324 325 326
		fmt.Printf(format, tr, td, ta, r, d, a)

		last = current
		lastPrintAt = tm
	}
}

B
Bomin Zhang 已提交
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
func startLogger(path string) error {
	if len(path) == 0 {
		return nil
	}

	f, e := os.Create(path)
	if e != nil {
		return e
	}

	chLog = make(chan string, 100)
	wgLog.Add(1)
	go func() {
		for s := range chLog {
			if f != nil {
				f.WriteString(s)
				f.WriteString("\n")
			}
		}
		f.Close()
		wgLog.Done()
	}()

	return nil
}

B
Bomin Zhang 已提交
353
func main() {
B
Bomin Zhang 已提交
354
	var concurrency uint
B
Bomin Zhang 已提交
355
	var logPath string
B
Bomin Zhang 已提交
356 357 358 359 360 361 362
	flag.StringVar(&host, "h", "localhost", "host name or IP address of TDengine server")
	flag.UintVar(&port, "P", 0, "port (default 0)")
	flag.StringVar(&database, "d", "test", "database name")
	flag.StringVar(&user, "u", "root", "user name")
	flag.StringVar(&password, "p", "taosdata", "password")
	flag.BoolVar(&fetch, "f", true, "fetch result or not")
	flag.UintVar(&concurrency, "c", 4, "concurrency, number of goroutines for query")
B
Bomin Zhang 已提交
363
	flag.StringVar(&logPath, "l", "", "path of log file (default: no log)")
B
Bomin Zhang 已提交
364 365
	flag.Parse()

B
Bomin Zhang 已提交
366 367 368 369 370
	if e := startLogger(logPath); e != nil {
		fmt.Println("failed to open log file:", e.Error())
		return
	}

371 372 373
	pathOrSQL := flag.Arg(0)
	if len(pathOrSQL) == 0 {
		pathOrSQL = "cases.json"
B
Bomin Zhang 已提交
374
	}
375
	if e := loadTestCase(pathOrSQL); e != nil {
B
Bomin Zhang 已提交
376
		fmt.Println("failed to load test cases:", e.Error())
B
Bomin Zhang 已提交
377 378 379 380 381
		return
	}

	rand.Seed(time.Now().UnixNano())

B
Bomin Zhang 已提交
382
	fmt.Printf("\nSERVER: %s    DATABASE: %s    CONCURRENCY: %d    FETCH DATA: %v\n\n", host, database, concurrency, fetch)
B
Bomin Zhang 已提交
383 384 385 386 387

	startAt = time.Now()
	printStat := getStatPrinter()
	printStat(startAt)

B
Bomin Zhang 已提交
388
	for i := uint(0); i < concurrency; i++ {
B
Bomin Zhang 已提交
389
		wgTest.Add(1)
B
Bomin Zhang 已提交
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
		go runTest()
	}

	interrupt := make(chan os.Signal, 1)
	signal.Notify(interrupt, os.Interrupt)
	ticker := time.NewTicker(time.Second)

	fmt.Println("Ctrl + C to exit....\033[1A")

LOOP:
	for {
		select {
		case <-interrupt:
			break LOOP
		case tm := <-ticker.C:
B
Bomin Zhang 已提交
405
			fmt.Print("\033[4A")
B
Bomin Zhang 已提交
406 407 408 409 410 411
			printStat(tm)
		}
	}

	atomic.StoreInt64(&shouldStop, 1)
	fmt.Print("\033[100D'Ctrl + C' received, Waiting started query to stop...")
B
Bomin Zhang 已提交
412
	wgTest.Wait()
B
Bomin Zhang 已提交
413

B
Bomin Zhang 已提交
414 415 416 417 418
	if chLog != nil {
		close(chLog)
		wgLog.Wait()
	}
	fmt.Print("\033[4A\033[100D")
B
Bomin Zhang 已提交
419 420 421
	printStat(time.Now())
	fmt.Println()
}