main.go 30.1 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/>.
 */

X
xieyinglin 已提交
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
package main

import (
	"bufio"
	"bytes"
	"database/sql"
	"encoding/json"
	"flag"
	"fmt"
	"io"
	"log"
	"os"
	"sort"
	"strconv"
	"strings"
	"sync"
	"time"

张金富 已提交
34
	dataImport "github.com/taosdata/TDengine/importSampleData/import"
dengyihao's avatar
TD-935  
dengyihao 已提交
35

36
	_ "github.com/taosdata/driver-go/taosSql"
X
xieyinglin 已提交
37 38 39
)

const (
张金富 已提交
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
	// 主键类型必须为 timestamp
	TIMESTAMP = "timestamp"

	// 样例数据中主键时间字段是 millisecond 还是 dateTime 格式
	DATETIME    = "datetime"
	MILLISECOND = "millisecond"

	DefaultStartTime int64 = -1
	DefaultInterval  int64 = 1 * 1000 // 导入的记录时间间隔,该设置只会在指定 auto=1 之后生效,否则会根据样例数据自动计算间隔时间。单位为毫秒,默认 1000。
	DefaultDelay     int64 = -1       //

	// 当 save 为 1 时保存统计信息的表名, 默认 statistic。
	DefaultStatisticTable = "statistic"

	// 样例数据文件格式,可以是 json 或 csv
	JsonFormat = "json"
	CsvFormat  = "csv"

	SuperTablePrefix = "s_" // 超级表前缀
	SubTablePrefix   = "t_" // 子表前缀

	DriverName      = "taosSql"
	StartTimeLayout = "2006-01-02 15:04:05.000"
	InsertPrefix    = "insert into "
X
xieyinglin 已提交
64 65 66
)

var (
张金富 已提交
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
	cfg          string // 导入配置文件路径,包含样例数据文件相关描述及对应 TDengine 配置信息。默认使用 config/cfg.toml
	cases        string // 需要导入的场景名称,该名称可从 -cfg 指定的配置文件中 [usecase] 查看,可同时导入多个场景,中间使用逗号分隔,如:sensor_info,camera_detection,默认为 sensor_info
	hnum         int    // 需要将样例数据进行横向扩展的倍数,假设原有样例数据包含 1 张子表 t_0 数据,指定 hnum 为 2 时会根据原有表名创建 t、t_1 两张子表。默认为 100。
	vnum         int    // 需要将样例数据进行纵向扩展的次数,如果设置为 0 代表将历史数据导入至当前时间后持续按照指定间隔导入。默认为 1000,表示将样例数据在时间轴上纵向复制1000 次
	thread       int    // 执行导入数据的线程数目,默认为 10
	batch        int    // 执行导入数据时的批量大小,默认为 100。批量是指一次写操作时,包含多少条记录
	auto         int    // 是否自动生成样例数据中的主键时间戳,1 是,0 否, 默认 0
	startTimeStr string // 导入的记录开始时间,格式为 "yyyy-MM-dd HH:mm:ss.SSS",不设置会使用样例数据中最小时间,设置后会忽略样例数据中的主键时间,会按照指定的 start 进行导入。如果 auto 为 1,则必须设置 start,默认为空
	interval     int64  // 导入的记录时间间隔,该设置只会在指定 auto=1 之后生效,否则会根据样例数据自动计算间隔时间。单位为毫秒,默认 1000
	host         string // 导入的 TDengine 服务器 IP,默认为 127.0.0.1
	port         int    // 导入的 TDengine 服务器端口,默认为 6030
	user         string // 导入的 TDengine 用户名,默认为 root
	password     string // 导入的 TDengine 用户密码,默认为 taosdata
	dropdb       int    // 导入数据之前是否删除数据库,1 是,0 否, 默认 0
	db           string // 导入的 TDengine 数据库名称,默认为 test_yyyyMMdd
	dbparam      string // 当指定的数据库不存在时,自动创建数据库时可选项配置参数,如 days 10 cache 16000 ablocks 4,默认为空
X
xieyinglin 已提交
83 84

	dataSourceName string
dengyihao's avatar
TD-935  
dengyihao 已提交
85
	startTime      int64
X
xieyinglin 已提交
86

dengyihao's avatar
TD-935  
dengyihao 已提交
87 88 89
	superTableConfigMap = make(map[string]*superTableConfig)
	subTableMap         = make(map[string]*dataRows)
	scaleTableNames     []string
X
xieyinglin 已提交
90 91 92

	scaleTableMap = make(map[string]*scaleTableInfo)

dengyihao's avatar
TD-935  
dengyihao 已提交
93
	successRows    []int64
X
xieyinglin 已提交
94
	lastStaticTime time.Time
dengyihao's avatar
TD-935  
dengyihao 已提交
95 96
	lastTotalRows  int64
	timeTicker     *time.Ticker
张金富 已提交
97 98 99 100
	delay          int64  // 当 vnum 设置为 0 时持续导入的时间间隔,默认为所有场景中最小记录间隔时间的一半,单位 ms。
	tick           int64  // 打印统计信息的时间间隔,默认 2000 ms。
	save           int    // 是否保存统计信息到 tdengine 的 statistic 表中,1 是,0 否, 默认 0。
	saveTable      string // 当 save 为 1 时保存统计信息的表名, 默认 statistic。
X
xieyinglin 已提交
101 102 103
)

type superTableConfig struct {
dengyihao's avatar
TD-935  
dengyihao 已提交
104 105 106
	startTime   int64
	endTime     int64
	cycleTime   int64
X
xieyinglin 已提交
107
	avgInterval int64
张金富 已提交
108
	config      dataImport.CaseConfig
X
xieyinglin 已提交
109 110 111 112
}

type scaleTableInfo struct {
	scaleTableName string
dengyihao's avatar
TD-935  
dengyihao 已提交
113 114
	subTableName   string
	insertRows     int64
X
xieyinglin 已提交
115 116
}

张金富 已提交
117 118 119 120
//type tableRows struct {
//	tableName string // tableName
//	value     string // values(...)
//}
X
xieyinglin 已提交
121 122

type dataRows struct {
dengyihao's avatar
TD-935  
dengyihao 已提交
123
	rows   []map[string]interface{}
张金富 已提交
124
	config dataImport.CaseConfig
X
xieyinglin 已提交
125 126 127 128 129 130 131
}

func (rows dataRows) Len() int {
	return len(rows.rows)
}

func (rows dataRows) Less(i, j int) bool {
张金富 已提交
132 133 134
	iTime := getPrimaryKey(rows.rows[i][rows.config.Timestamp])
	jTime := getPrimaryKey(rows.rows[j][rows.config.Timestamp])
	return iTime < jTime
X
xieyinglin 已提交
135 136 137 138 139 140 141 142 143 144 145 146 147
}

func (rows dataRows) Swap(i, j int) {
	rows.rows[i], rows.rows[j] = rows.rows[j], rows.rows[i]
}

func getPrimaryKey(value interface{}) int64 {
	val, _ := value.(int64)
	//time, _ := strconv.ParseInt(str, 10, 64)
	return val
}

func init() {
张金富 已提交
148
	parseArg() // parse argument
X
xieyinglin 已提交
149 150

	if db == "" {
张金富 已提交
151
		// 导入的 TDengine 数据库名称,默认为 test_yyyyMMdd
dengyihao's avatar
TD-935  
dengyihao 已提交
152
		db = fmt.Sprintf("test_%s", time.Now().Format("20060102"))
X
xieyinglin 已提交
153 154
	}

张金富 已提交
155
	if auto == 1 && len(startTimeStr) == 0 {
X
xieyinglin 已提交
156 157 158
		log.Fatalf("startTime must be set when auto is 1, the format is \"yyyy-MM-dd HH:mm:ss.SSS\" ")
	}

张金富 已提交
159 160
	if len(startTimeStr) != 0 {
		t, err := time.ParseInLocation(StartTimeLayout, strings.TrimSpace(startTimeStr), time.Local)
X
xieyinglin 已提交
161
		if err != nil {
张金富 已提交
162
			log.Fatalf("param startTime %s error, %s\n", startTimeStr, err)
X
xieyinglin 已提交
163 164 165
		}

		startTime = t.UnixNano() / 1e6 // as millisecond
dengyihao's avatar
TD-935  
dengyihao 已提交
166
	} else {
张金富 已提交
167
		startTime = DefaultStartTime
X
xieyinglin 已提交
168 169 170 171 172 173 174 175 176 177 178
	}

	dataSourceName = fmt.Sprintf("%s:%s@/tcp(%s:%d)/", user, password, host, port)

	printArg()

	log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
}

func main() {

张金富 已提交
179
	importConfig := dataImport.LoadConfig(cfg)
X
xieyinglin 已提交
180

张金富 已提交
181
	var caseMinInterval int64 = -1
X
xieyinglin 已提交
182

X
xieyinglin 已提交
183 184 185 186 187 188 189 190 191 192
	for _, userCase := range strings.Split(cases, ",") {
		caseConfig, ok := importConfig.UserCases[userCase]

		if !ok {
			log.Println("not exist case: ", userCase)
			continue
		}

		checkUserCaseConfig(userCase, &caseConfig)

张金富 已提交
193
		// read file as map array
X
xieyinglin 已提交
194 195 196 197 198 199 200 201
		fileRows := readFile(caseConfig)
		log.Printf("case [%s] sample data file contains %d rows.\n", userCase, len(fileRows.rows))

		if len(fileRows.rows) == 0 {
			log.Printf("there is no valid line in file %s\n", caseConfig.FilePath)
			continue
		}

张金富 已提交
202
		_, exists := superTableConfigMap[caseConfig.StName]
X
xieyinglin 已提交
203
		if !exists {
张金富 已提交
204
			superTableConfigMap[caseConfig.StName] = &superTableConfig{config: caseConfig}
X
xieyinglin 已提交
205
		} else {
张金富 已提交
206
			log.Fatalf("the stname of case %s already exist.\n", caseConfig.StName)
X
xieyinglin 已提交
207 208 209 210 211
		}

		var start, cycleTime, avgInterval int64 = getSuperTableTimeConfig(fileRows)

		// set super table's startTime, cycleTime and avgInterval
张金富 已提交
212 213 214
		superTableConfigMap[caseConfig.StName].startTime = start
		superTableConfigMap[caseConfig.StName].cycleTime = cycleTime
		superTableConfigMap[caseConfig.StName].avgInterval = avgInterval
X
xieyinglin 已提交
215

张金富 已提交
216 217
		if caseMinInterval == -1 || caseMinInterval > avgInterval {
			caseMinInterval = avgInterval
X
xieyinglin 已提交
218 219
		}

张金富 已提交
220
		startStr := time.Unix(0, start*int64(time.Millisecond)).Format(StartTimeLayout)
X
xieyinglin 已提交
221 222 223
		log.Printf("case [%s] startTime %s(%d), average dataInterval %d ms, cycleTime %d ms.\n", userCase, startStr, start, avgInterval, cycleTime)
	}

张金富 已提交
224
	if DefaultDelay == delay {
X
xieyinglin 已提交
225
		// default delay
张金富 已提交
226
		delay = caseMinInterval / 2
X
xieyinglin 已提交
227
		if delay < 1 {
dengyihao's avatar
TD-935  
dengyihao 已提交
228
			delay = 1
X
xieyinglin 已提交
229 230 231 232
		}
		log.Printf("actual delay is %d ms.", delay)
	}

X
xieyinglin 已提交
233 234 235 236 237 238 239 240 241 242
	superTableNum := len(superTableConfigMap)
	if superTableNum == 0 {
		log.Fatalln("no valid file, exited")
	}

	start := time.Now()
	// create super table
	createSuperTable(superTableConfigMap)
	log.Printf("create %d superTable ,used %d ms.\n", superTableNum, time.Since(start)/1e6)

张金富 已提交
243
	// create sub table
X
xieyinglin 已提交
244 245 246 247 248 249 250 251 252 253 254 255 256
	start = time.Now()
	createSubTable(subTableMap)
	log.Printf("create %d times of %d subtable ,all %d tables, used %d ms.\n", hnum, len(subTableMap), len(scaleTableMap), time.Since(start)/1e6)

	subTableNum := len(scaleTableMap)

	if subTableNum < thread {
		thread = subTableNum
	}

	filePerThread := subTableNum / thread
	leftFileNum := subTableNum % thread

dengyihao's avatar
TD-935  
dengyihao 已提交
257
	var wg sync.WaitGroup
X
xieyinglin 已提交
258 259 260

	start = time.Now()

X
xieyinglin 已提交
261 262
	successRows = make([]int64, thread)

X
xieyinglin 已提交
263 264 265 266 267 268 269 270
	startIndex, endIndex := 0, filePerThread
	for i := 0; i < thread; i++ {
		// start thread
		if i < leftFileNum {
			endIndex++
		}
		wg.Add(1)

X
xieyinglin 已提交
271
		go insertData(i, startIndex, endIndex, &wg, successRows)
X
xieyinglin 已提交
272 273 274
		startIndex, endIndex = endIndex, endIndex+filePerThread
	}

X
xieyinglin 已提交
275 276 277
	lastStaticTime = time.Now()
	timeTicker = time.NewTicker(time.Millisecond * time.Duration(tick))
	go staticSpeed()
X
xieyinglin 已提交
278 279
	wg.Wait()

dengyihao's avatar
TD-935  
dengyihao 已提交
280
	usedTime := time.Since(start)
X
xieyinglin 已提交
281

X
xieyinglin 已提交
282 283
	total := getTotalRows(successRows)

dengyihao's avatar
TD-935  
dengyihao 已提交
284
	log.Printf("finished insert %d rows, used %d ms, speed %d rows/s", total, usedTime/1e6, total*1e3/usedTime.Milliseconds())
X
xieyinglin 已提交
285 286 287

	if vnum == 0 {
		// continue waiting for insert data
dengyihao's avatar
TD-935  
dengyihao 已提交
288 289
		wait := make(chan string)
		v := <-wait
X
xieyinglin 已提交
290
		log.Printf("program receive %s, exited.\n", v)
dengyihao's avatar
TD-935  
dengyihao 已提交
291
	} else {
X
xieyinglin 已提交
292
		timeTicker.Stop()
X
xieyinglin 已提交
293 294 295 296
	}

}

dengyihao's avatar
TD-935  
dengyihao 已提交
297
func staticSpeed() {
X
xieyinglin 已提交
298 299 300 301 302

	connection := getConnection()
	defer connection.Close()

	if save == 1 {
张金富 已提交
303
		_, _ = connection.Exec("use " + db)
dengyihao's avatar
TD-935  
dengyihao 已提交
304
		_, err := connection.Exec("create table if not exists " + saveTable + "(ts timestamp, speed int)")
X
xieyinglin 已提交
305
		if err != nil {
X
xieyinglin 已提交
306
			log.Fatalf("create %s Table error: %s\n", saveTable, err)
X
xieyinglin 已提交
307 308 309 310 311
		}
	}

	for {
		<-timeTicker.C
dengyihao's avatar
TD-935  
dengyihao 已提交
312

X
xieyinglin 已提交
313 314
		currentTime := time.Now()
		usedTime := currentTime.UnixNano() - lastStaticTime.UnixNano()
dengyihao's avatar
TD-935  
dengyihao 已提交
315

X
xieyinglin 已提交
316 317
		total := getTotalRows(successRows)
		currentSuccessRows := total - lastTotalRows
dengyihao's avatar
TD-935  
dengyihao 已提交
318

张金富 已提交
319
		speed := currentSuccessRows * 1e9 / usedTime
X
xieyinglin 已提交
320 321 322
		log.Printf("insert %d rows, used %d ms, speed %d rows/s", currentSuccessRows, usedTime/1e6, speed)

		if save == 1 {
X
xieyinglin 已提交
323
			insertSql := fmt.Sprintf("insert into %s values(%d, %d)", saveTable, currentTime.UnixNano()/1e6, speed)
张金富 已提交
324
			_, _ = connection.Exec(insertSql)
X
xieyinglin 已提交
325
		}
dengyihao's avatar
TD-935  
dengyihao 已提交
326

X
xieyinglin 已提交
327 328 329 330 331 332
		lastStaticTime = currentTime
		lastTotalRows = total
	}

}

dengyihao's avatar
TD-935  
dengyihao 已提交
333
func getTotalRows(successRows []int64) int64 {
X
xieyinglin 已提交
334 335 336 337 338 339 340
	var total int64 = 0
	for j := 0; j < len(successRows); j++ {
		total += successRows[j]
	}
	return total
}

dengyihao's avatar
TD-935  
dengyihao 已提交
341
func getSuperTableTimeConfig(fileRows dataRows) (start, cycleTime, avgInterval int64) {
X
xieyinglin 已提交
342 343 344 345 346
	if auto == 1 {
		// use auto generate data time
		start = startTime
		avgInterval = interval
		maxTableRows := normalizationDataWithSameInterval(fileRows, avgInterval)
dengyihao's avatar
TD-935  
dengyihao 已提交
347
		cycleTime = maxTableRows*avgInterval + avgInterval
X
xieyinglin 已提交
348 349 350 351

	} else {

		// use the sample data primary timestamp
张金富 已提交
352
		sort.Sort(fileRows) // sort the file data by the primaryKey
X
xieyinglin 已提交
353 354 355 356
		minTime := getPrimaryKey(fileRows.rows[0][fileRows.config.Timestamp])
		maxTime := getPrimaryKey(fileRows.rows[len(fileRows.rows)-1][fileRows.config.Timestamp])

		start = minTime // default startTime use the minTime
张金富 已提交
357 358
		// 设置了start时间的话 按照start来
		if DefaultStartTime != startTime {
X
xieyinglin 已提交
359 360 361 362 363 364 365
			start = startTime
		}

		tableNum := normalizationData(fileRows, minTime)

		if minTime == maxTime {
			avgInterval = interval
dengyihao's avatar
TD-935  
dengyihao 已提交
366 367
			cycleTime = tableNum*avgInterval + avgInterval
		} else {
X
xieyinglin 已提交
368 369 370
			avgInterval = (maxTime - minTime) / int64(len(fileRows.rows)) * tableNum
			cycleTime = maxTime - minTime + avgInterval
		}
dengyihao's avatar
TD-935  
dengyihao 已提交
371

X
xieyinglin 已提交
372 373 374 375 376 377 378 379 380
	}
	return
}

func createSubTable(subTableMaps map[string]*dataRows) {

	connection := getConnection()
	defer connection.Close()

张金富 已提交
381
	_, _ = connection.Exec("use " + db)
X
xieyinglin 已提交
382 383

	createTablePrefix := "create table if not exists "
张金富 已提交
384
	var buffer bytes.Buffer
X
xieyinglin 已提交
385 386
	for subTableName := range subTableMaps {

张金富 已提交
387 388
		superTableName := getSuperTableName(subTableMaps[subTableName].config.StName)
		firstRowValues := subTableMaps[subTableName].rows[0] // the first rows values as tags
X
xieyinglin 已提交
389

张金富 已提交
390
		// create table t using superTable tags(...);
X
xieyinglin 已提交
391 392 393 394
		for i := 0; i < hnum; i++ {
			tableName := getScaleSubTableName(subTableName, i)

			scaleTableMap[tableName] = &scaleTableInfo{
dengyihao's avatar
TD-935  
dengyihao 已提交
395 396
				subTableName: subTableName,
				insertRows:   0,
X
xieyinglin 已提交
397 398 399
			}
			scaleTableNames = append(scaleTableNames, tableName)

张金富 已提交
400 401 402 403 404
			buffer.WriteString(createTablePrefix)
			buffer.WriteString(tableName)
			buffer.WriteString(" using ")
			buffer.WriteString(superTableName)
			buffer.WriteString(" tags(")
dengyihao's avatar
TD-935  
dengyihao 已提交
405
			for _, tag := range subTableMaps[subTableName].config.Tags {
张金富 已提交
406 407 408
				tagValue := fmt.Sprintf("%v", firstRowValues[strings.ToLower(tag.Name)])
				buffer.WriteString("'" + tagValue + "'")
				buffer.WriteString(",")
X
xieyinglin 已提交
409
			}
张金富 已提交
410 411
			buffer.Truncate(buffer.Len() - 1)
			buffer.WriteString(")")
X
xieyinglin 已提交
412

张金富 已提交
413 414
			createTableSql := buffer.String()
			buffer.Reset()
X
xieyinglin 已提交
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435

			//log.Printf("create table: %s\n", createTableSql)
			_, err := connection.Exec(createTableSql)
			if err != nil {
				log.Fatalf("create table error: %s\n", err)
			}
		}
	}
}

func createSuperTable(superTableConfigMap map[string]*superTableConfig) {

	connection := getConnection()
	defer connection.Close()

	if dropdb == 1 {
		dropDbSql := "drop database if exists " + db
		_, err := connection.Exec(dropDbSql) // drop database if exists
		if err != nil {
			log.Fatalf("drop database error: %s\n", err)
		}
张金富 已提交
436
		log.Printf("dropdb: %s\n", dropDbSql)
X
xieyinglin 已提交
437 438 439 440 441 442 443 444 445 446
	}

	createDbSql := "create database if not exists " + db + " " + dbparam

	_, err := connection.Exec(createDbSql) // create database if not exists
	if err != nil {
		log.Fatalf("create database error: %s\n", err)
	}
	log.Printf("createDb: %s\n", createDbSql)

张金富 已提交
447
	_, _ = connection.Exec("use " + db)
X
xieyinglin 已提交
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466

	prefix := "create table if not exists "
	var buffer bytes.Buffer
	//CREATE TABLE <stable_name> (<field_name> TIMESTAMP, field_name1 field_type,…) TAGS(tag_name tag_type, …)
	for key := range superTableConfigMap {

		buffer.WriteString(prefix)
		buffer.WriteString(getSuperTableName(key))
		buffer.WriteString("(")

		superTableConf := superTableConfigMap[key]

		buffer.WriteString(superTableConf.config.Timestamp)
		buffer.WriteString(" timestamp, ")

		for _, field := range superTableConf.config.Fields {
			buffer.WriteString(field.Name + " " + field.Type + ",")
		}

dengyihao's avatar
TD-935  
dengyihao 已提交
467
		buffer.Truncate(buffer.Len() - 1)
X
xieyinglin 已提交
468 469 470 471 472 473
		buffer.WriteString(") tags( ")

		for _, tag := range superTableConf.config.Tags {
			buffer.WriteString(tag.Name + " " + tag.Type + ",")
		}

dengyihao's avatar
TD-935  
dengyihao 已提交
474
		buffer.Truncate(buffer.Len() - 1)
X
xieyinglin 已提交
475 476 477 478 479
		buffer.WriteString(")")

		createSql := buffer.String()
		buffer.Reset()

张金富 已提交
480
		//log.Printf("superTable: %s\n", createSql)
X
xieyinglin 已提交
481 482 483 484 485 486 487 488
		_, err = connection.Exec(createSql)
		if err != nil {
			log.Fatalf("create supertable error: %s\n", err)
		}
	}

}

张金富 已提交
489 490
func getScaleSubTableName(subTableName string, hNum int) string {
	if hNum == 0 {
dengyihao's avatar
TD-935  
dengyihao 已提交
491
		return subTableName
X
xieyinglin 已提交
492
	}
张金富 已提交
493
	return fmt.Sprintf("%s_%d", subTableName, hNum)
X
xieyinglin 已提交
494 495
}

张金富 已提交
496 497
func getSuperTableName(stName string) string {
	return SuperTablePrefix + stName
X
xieyinglin 已提交
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
}

/**
* normalizationData , and return the num of subTables
 */
func normalizationData(fileRows dataRows, minTime int64) int64 {

	var tableNum int64 = 0
	for _, row := range fileRows.rows {
		// get subTableName
		tableValue := getSubTableNameValue(row[fileRows.config.SubTableName])
		if len(tableValue) == 0 {
			continue
		}

		row[fileRows.config.Timestamp] = getPrimaryKey(row[fileRows.config.Timestamp]) - minTime

张金富 已提交
515
		subTableName := getSubTableName(tableValue, fileRows.config.StName)
X
xieyinglin 已提交
516 517 518 519

		value, ok := subTableMap[subTableName]
		if !ok {
			subTableMap[subTableName] = &dataRows{
dengyihao's avatar
TD-935  
dengyihao 已提交
520 521
				rows:   []map[string]interface{}{row},
				config: fileRows.config,
X
xieyinglin 已提交
522 523 524
			}

			tableNum++
dengyihao's avatar
TD-935  
dengyihao 已提交
525
		} else {
X
xieyinglin 已提交
526 527 528 529 530 531 532
			value.rows = append(value.rows, row)
		}
	}
	return tableNum
}

// return the maximum table rows
dengyihao's avatar
TD-935  
dengyihao 已提交
533
func normalizationDataWithSameInterval(fileRows dataRows, avgInterval int64) int64 {
X
xieyinglin 已提交
534
	// subTableMap
dengyihao's avatar
TD-935  
dengyihao 已提交
535
	currSubTableMap := make(map[string]*dataRows)
X
xieyinglin 已提交
536 537 538 539 540 541 542
	for _, row := range fileRows.rows {
		// get subTableName
		tableValue := getSubTableNameValue(row[fileRows.config.SubTableName])
		if len(tableValue) == 0 {
			continue
		}

张金富 已提交
543
		subTableName := getSubTableName(tableValue, fileRows.config.StName)
X
xieyinglin 已提交
544 545 546 547 548

		value, ok := currSubTableMap[subTableName]
		if !ok {
			row[fileRows.config.Timestamp] = 0
			currSubTableMap[subTableName] = &dataRows{
dengyihao's avatar
TD-935  
dengyihao 已提交
549 550
				rows:   []map[string]interface{}{row},
				config: fileRows.config,
X
xieyinglin 已提交
551
			}
dengyihao's avatar
TD-935  
dengyihao 已提交
552
		} else {
X
xieyinglin 已提交
553 554 555 556 557 558
			row[fileRows.config.Timestamp] = int64(len(value.rows)) * avgInterval
			value.rows = append(value.rows, row)
		}

	}

张金富 已提交
559
	var maxRows, tableRows = 0, 0
dengyihao's avatar
TD-935  
dengyihao 已提交
560
	for tableName := range currSubTableMap {
X
xieyinglin 已提交
561 562 563 564 565 566 567 568 569 570
		tableRows = len(currSubTableMap[tableName].rows)
		subTableMap[tableName] = currSubTableMap[tableName] // add to global subTableMap
		if tableRows > maxRows {
			maxRows = tableRows
		}
	}

	return int64(maxRows)
}

dengyihao's avatar
TD-935  
dengyihao 已提交
571
func getSubTableName(subTableValue string, superTableName string) string {
张金富 已提交
572
	return SubTablePrefix + subTableValue + "_" + superTableName
X
xieyinglin 已提交
573 574
}

dengyihao's avatar
TD-935  
dengyihao 已提交
575
func insertData(threadIndex, start, end int, wg *sync.WaitGroup, successRows []int64) {
X
xieyinglin 已提交
576 577 578 579
	connection := getConnection()
	defer connection.Close()
	defer wg.Done()

张金富 已提交
580
	_, _ = connection.Exec("use " + db) // use db
X
xieyinglin 已提交
581

X
xieyinglin 已提交
582 583
	log.Printf("thread-%d start insert into [%d, %d) subtables.\n", threadIndex, start, end)

X
xieyinglin 已提交
584
	num := 0
X
xieyinglin 已提交
585
	subTables := scaleTableNames[start:end]
张金富 已提交
586
	var buffer bytes.Buffer
X
xieyinglin 已提交
587
	for {
X
xieyinglin 已提交
588 589 590
		var currSuccessRows int64
		var appendRows int
		var lastTableName string
X
xieyinglin 已提交
591

张金富 已提交
592
		buffer.WriteString(InsertPrefix)
X
xieyinglin 已提交
593 594 595 596 597

		for _, tableName := range subTables {

			subTableInfo := subTableMap[scaleTableMap[tableName].subTableName]
			subTableRows := int64(len(subTableInfo.rows))
张金富 已提交
598
			superTableConf := superTableConfigMap[subTableInfo.config.StName]
X
xieyinglin 已提交
599 600 601 602 603

			tableStartTime := superTableConf.startTime
			var tableEndTime int64
			if vnum == 0 {
				// need continue generate data
dengyihao's avatar
TD-935  
dengyihao 已提交
604 605 606
				tableEndTime = time.Now().UnixNano() / 1e6
			} else {
				tableEndTime = tableStartTime + superTableConf.cycleTime*int64(vnum) - superTableConf.avgInterval
X
xieyinglin 已提交
607 608 609 610 611 612 613 614 615
			}

			insertRows := scaleTableMap[tableName].insertRows

			for {
				loopNum := insertRows / subTableRows
				rowIndex := insertRows % subTableRows
				currentRow := subTableInfo.rows[rowIndex]

dengyihao's avatar
TD-935  
dengyihao 已提交
616
				currentTime := getPrimaryKey(currentRow[subTableInfo.config.Timestamp]) + loopNum*superTableConf.cycleTime + tableStartTime
X
xieyinglin 已提交
617 618
				if currentTime <= tableEndTime {
					// append
dengyihao's avatar
TD-935  
dengyihao 已提交
619

X
xieyinglin 已提交
620
					if lastTableName != tableName {
张金富 已提交
621 622
						buffer.WriteString(tableName)
						buffer.WriteString(" values")
X
xieyinglin 已提交
623 624 625
					}
					lastTableName = tableName

张金富 已提交
626 627 628
					buffer.WriteString("(")
					buffer.WriteString(fmt.Sprintf("%v", currentTime))
					buffer.WriteString(",")
dengyihao's avatar
TD-935  
dengyihao 已提交
629 630

					for _, field := range subTableInfo.config.Fields {
631
						buffer.WriteString(getFieldValue(currentRow[strings.ToLower(field.Name)],field.Type))
张金富 已提交
632
						buffer.WriteString(",")
X
xieyinglin 已提交
633
					}
X
xieyinglin 已提交
634

张金富 已提交
635 636
					buffer.Truncate(buffer.Len() - 1)
					buffer.WriteString(") ")
X
xieyinglin 已提交
637 638

					appendRows++
X
xieyinglin 已提交
639
					insertRows++
dengyihao's avatar
TD-935  
dengyihao 已提交
640
					if appendRows == batch {
张金富 已提交
641 642
						// executeBatch
						insertSql := buffer.String()
X
xieyinglin 已提交
643 644
						affectedRows := executeBatchInsert(insertSql, connection)

X
xieyinglin 已提交
645 646 647
						successRows[threadIndex] += affectedRows
						currSuccessRows += affectedRows

张金富 已提交
648 649
						buffer.Reset()
						buffer.WriteString(InsertPrefix)
X
xieyinglin 已提交
650 651
						lastTableName = ""
						appendRows = 0
X
xieyinglin 已提交
652
					}
dengyihao's avatar
TD-935  
dengyihao 已提交
653
				} else {
X
xieyinglin 已提交
654 655 656 657 658 659 660 661
					// finished insert current table
					break
				}
			}

			scaleTableMap[tableName].insertRows = insertRows

		}
dengyihao's avatar
TD-935  
dengyihao 已提交
662

X
xieyinglin 已提交
663
		// left := len(rows)
dengyihao's avatar
TD-935  
dengyihao 已提交
664
		if appendRows > 0 {
张金富 已提交
665 666
			// executeBatch
			insertSql := buffer.String()
X
xieyinglin 已提交
667
			affectedRows := executeBatchInsert(insertSql, connection)
dengyihao's avatar
TD-935  
dengyihao 已提交
668

X
xieyinglin 已提交
669 670 671
			successRows[threadIndex] += affectedRows
			currSuccessRows += affectedRows

张金富 已提交
672
			buffer.Reset()
X
xieyinglin 已提交
673 674
		}

X
xieyinglin 已提交
675
		// log.Printf("thread-%d finished insert %d rows, used %d ms.", threadIndex, currSuccessRows, time.Since(threadStartTime)/1e6)
X
xieyinglin 已提交
676 677 678

		if vnum != 0 {
			// thread finished insert data
X
xieyinglin 已提交
679
			// log.Printf("thread-%d exit\n", threadIndex)
X
xieyinglin 已提交
680 681 682
			break
		}

dengyihao's avatar
TD-935  
dengyihao 已提交
683
		if num == 0 {
X
xieyinglin 已提交
684 685
			wg.Done() //finished insert history data
			num++
X
xieyinglin 已提交
686 687
		}

X
xieyinglin 已提交
688 689 690 691
		if currSuccessRows == 0 {
			// log.Printf("thread-%d start to sleep %d ms.", threadIndex, delay)
			time.Sleep(time.Duration(delay) * time.Millisecond)
		}
X
xieyinglin 已提交
692

X
xieyinglin 已提交
693
		// need continue insert data
X
xieyinglin 已提交
694 695 696 697 698
	}

}

func executeBatchInsert(insertSql string, connection *sql.DB) int64 {
张金富 已提交
699 700 701
	result, err := connection.Exec(insertSql)
	if err != nil {
		log.Printf("execute insertSql %s error, %s\n", insertSql, err)
X
xieyinglin 已提交
702 703 704 705 706 707 708 709 710
		return 0
	}
	affected, _ := result.RowsAffected()
	if affected < 0 {
		affected = 0
	}
	return affected
}

711 712 713 714
func getFieldValue(fieldValue interface{},fieldtype interface{}) string {
	if fieldtype == "timestamp" || fieldtype == "bigint"  {
		return fmt.Sprintf("%v", fieldValue)
	}
X
xieyinglin 已提交
715 716 717
	return fmt.Sprintf("'%v'", fieldValue)
}

dengyihao's avatar
TD-935  
dengyihao 已提交
718
func getConnection() *sql.DB {
张金富 已提交
719
	db, err := sql.Open(DriverName, dataSourceName)
X
xieyinglin 已提交
720 721 722 723 724 725 726 727 728 729
	if err != nil {
		panic(err)
	}
	return db
}

func getSubTableNameValue(suffix interface{}) string {
	return fmt.Sprintf("%v", suffix)
}

张金富 已提交
730
func readFile(config dataImport.CaseConfig) dataRows {
X
xieyinglin 已提交
731
	fileFormat := strings.ToLower(config.Format)
张金富 已提交
732
	if fileFormat == JsonFormat {
X
xieyinglin 已提交
733
		return readJSONFile(config)
张金富 已提交
734
	} else if fileFormat == CsvFormat {
X
xieyinglin 已提交
735 736 737 738 739 740 741
		return readCSVFile(config)
	}

	log.Printf("the file %s is not supported yet\n", config.FilePath)
	return dataRows{}
}

张金富 已提交
742
func readCSVFile(config dataImport.CaseConfig) dataRows {
X
xieyinglin 已提交
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
	var rows dataRows
	f, err := os.Open(config.FilePath)
	if err != nil {
		log.Printf("Error: %s, %s\n", config.FilePath, err)
		return rows
	}
	defer f.Close()

	r := bufio.NewReader(f)

	//read the first line as title
	lineBytes, _, err := r.ReadLine()
	if err == io.EOF {
		log.Printf("the file %s is empty\n", config.FilePath)
		return rows
	}
	line := strings.ToLower(string(lineBytes))
	titles := strings.Split(line, config.Separator)
	if len(titles) < 3 {
张金富 已提交
762
		// need suffix、 primaryKey and at least one other field
X
xieyinglin 已提交
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
		log.Printf("the first line of file %s should be title row, and at least 3 field.\n", config.FilePath)
		return rows
	}

	rows.config = config

	var lineNum = 0
	for {
		// read data row
		lineBytes, _, err = r.ReadLine()
		lineNum++
		if err == io.EOF {
			break
		}
		// fmt.Println(line)
		rowData := strings.Split(string(lineBytes), config.Separator)

		dataMap := make(map[string]interface{})
		for i, title := range titles {
			title = strings.TrimSpace(title)
			if i < len(rowData) {
				dataMap[title] = strings.TrimSpace(rowData[i])
			} else {
				dataMap[title] = ""
			}
		}

		// if the suffix valid
		if !existMapKeyAndNotEmpty(config.Timestamp, dataMap) {
			log.Printf("the Timestamp[%s] of line %d is empty, will filtered.\n", config.Timestamp, lineNum)
			continue
		}

		// if the primary key valid
张金富 已提交
797
		primaryKeyValue := getPrimaryKeyMilliSec(config.Timestamp, config.TimestampType, config.TimestampTypeFormat, dataMap)
X
xieyinglin 已提交
798 799 800 801 802 803 804 805 806 807 808 809
		if primaryKeyValue == -1 {
			log.Printf("the Timestamp[%s] of line %d is not valid, will filtered.\n", config.Timestamp, lineNum)
			continue
		}

		dataMap[config.Timestamp] = primaryKeyValue

		rows.rows = append(rows.rows, dataMap)
	}
	return rows
}

张金富 已提交
810
func readJSONFile(config dataImport.CaseConfig) dataRows {
X
xieyinglin 已提交
811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847

	var rows dataRows
	f, err := os.Open(config.FilePath)
	if err != nil {
		log.Printf("Error: %s, %s\n", config.FilePath, err)
		return rows
	}
	defer f.Close()

	r := bufio.NewReader(f)
	//log.Printf("file size %d\n", r.Size())

	rows.config = config
	var lineNum = 0
	for {
		lineBytes, _, err := r.ReadLine()
		lineNum++
		if err == io.EOF {
			break
		}

		line := make(map[string]interface{})
		err = json.Unmarshal(lineBytes, &line)

		if err != nil {
			log.Printf("line [%d] of file %s parse error, reason:  %s\n", lineNum, config.FilePath, err)
			continue
		}

		// transfer the key to lowercase
		lowerMapKey(line)

		if !existMapKeyAndNotEmpty(config.SubTableName, line) {
			log.Printf("the SubTableName[%s] of line %d is empty, will filtered.\n", config.SubTableName, lineNum)
			continue
		}

张金富 已提交
848
		primaryKeyValue := getPrimaryKeyMilliSec(config.Timestamp, config.TimestampType, config.TimestampTypeFormat, line)
X
xieyinglin 已提交
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
		if primaryKeyValue == -1 {
			log.Printf("the Timestamp[%s] of line %d is not valid, will filtered.\n", config.Timestamp, lineNum)
			continue
		}

		line[config.Timestamp] = primaryKeyValue

		rows.rows = append(rows.rows, line)
	}

	return rows
}

/**
* get primary key as millisecond , otherwise return -1
 */
张金富 已提交
865
func getPrimaryKeyMilliSec(key string, valueType string, valueFormat string, line map[string]interface{}) int64 {
X
xieyinglin 已提交
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
	if !existMapKeyAndNotEmpty(key, line) {
		return -1
	}
	if DATETIME == valueType {
		// transfer the datetime to milliseconds
		return parseMillisecond(line[key], valueFormat)
	}

	value, err := strconv.ParseInt(fmt.Sprintf("%v", line[key]), 10, 64)
	// as millisecond num
	if err != nil {
		return -1
	}
	return value
}

// parseMillisecond parse the dateStr to millisecond, return -1 if failed
func parseMillisecond(str interface{}, layout string) int64 {
	value, ok := str.(string)
	if !ok {
		return -1
	}

	t, err := time.ParseInLocation(layout, strings.TrimSpace(value), time.Local)

	if err != nil {
		log.Println(err)
		return -1
	}
dengyihao's avatar
TD-935  
dengyihao 已提交
895
	return t.UnixNano() / 1e6
X
xieyinglin 已提交
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919
}

// lowerMapKey transfer all the map key to lowercase
func lowerMapKey(maps map[string]interface{}) {
	for key := range maps {
		value := maps[key]
		delete(maps, key)
		maps[strings.ToLower(key)] = value
	}
}

func existMapKeyAndNotEmpty(key string, maps map[string]interface{}) bool {
	value, ok := maps[key]
	if !ok {
		return false
	}

	str, err := value.(string)
	if err && len(str) == 0 {
		return false
	}
	return true
}

张金富 已提交
920
func checkUserCaseConfig(caseName string, caseConfig *dataImport.CaseConfig) {
X
xieyinglin 已提交
921

张金富 已提交
922
	if len(caseConfig.StName) == 0 {
X
xieyinglin 已提交
923 924 925
		log.Fatalf("the stname of case %s can't be empty\n", caseName)
	}

张金富 已提交
926
	caseConfig.StName = strings.ToLower(caseConfig.StName)
X
xieyinglin 已提交
927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953

	if len(caseConfig.Tags) == 0 {
		log.Fatalf("the tags of case %s can't be empty\n", caseName)
	}

	if len(caseConfig.Fields) == 0 {
		log.Fatalf("the fields of case %s can't be empty\n", caseName)
	}

	if len(caseConfig.SubTableName) == 0 {
		log.Fatalf("the suffix of case %s can't be empty\n", caseName)
	}

	caseConfig.SubTableName = strings.ToLower(caseConfig.SubTableName)

	caseConfig.Timestamp = strings.ToLower(caseConfig.Timestamp)

	var timestampExist = false
	for i, field := range caseConfig.Fields {
		if strings.EqualFold(field.Name, caseConfig.Timestamp) {
			if strings.ToLower(field.Type) != TIMESTAMP {
				log.Fatalf("case %s's primaryKey %s field type is %s, it must be timestamp\n", caseName, caseConfig.Timestamp, field.Type)
			}
			timestampExist = true
			if i < len(caseConfig.Fields)-1 {
				// delete middle item,  a = a[:i+copy(a[i:], a[i+1:])]
				caseConfig.Fields = caseConfig.Fields[:i+copy(caseConfig.Fields[i:], caseConfig.Fields[i+1:])]
dengyihao's avatar
TD-935  
dengyihao 已提交
954
			} else {
X
xieyinglin 已提交
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
				// delete the last item
				caseConfig.Fields = caseConfig.Fields[:len(caseConfig.Fields)-1]
			}
			break
		}
	}

	if !timestampExist {
		log.Fatalf("case %s primaryKey %s is not exist in fields\n", caseName, caseConfig.Timestamp)
	}

	caseConfig.TimestampType = strings.ToLower(caseConfig.TimestampType)
	if caseConfig.TimestampType != MILLISECOND && caseConfig.TimestampType != DATETIME {
		log.Fatalf("case %s's timestampType %s error, only can be timestamp or datetime\n", caseName, caseConfig.TimestampType)
	}

	if caseConfig.TimestampType == DATETIME && len(caseConfig.TimestampTypeFormat) == 0 {
		log.Fatalf("case %s's timestampTypeFormat %s can't be empty when timestampType is datetime\n", caseName, caseConfig.TimestampTypeFormat)
	}

}

func parseArg() {
张金富 已提交
978 979
	flag.StringVar(&cfg, "cfg", "config/cfg.toml", "configuration file which describes useCase and data format.")
	flag.StringVar(&cases, "cases", "sensor_info", "useCase for dataset to be imported. Multiple choices can be separated by comma, for example, -cases sensor_info,camera_detection.")
X
xieyinglin 已提交
980 981
	flag.IntVar(&hnum, "hnum", 100, "magnification factor of the sample tables. For example, if hnum is 100 and in the sample data there are 10 tables, then 10x100=1000 tables will be created in the database.")
	flag.IntVar(&vnum, "vnum", 1000, "copies of the sample records in each table. If set to 0,this program will never stop simulating and importing data even if the timestamp has passed current time.")
张金富 已提交
982
	flag.Int64Var(&delay, "delay", DefaultDelay, "the delay time interval(millisecond) to continue generating data when vnum set 0.")
X
xieyinglin 已提交
983 984
	flag.Int64Var(&tick, "tick", 2000, "the tick time interval(millisecond) to print statistic info.")
	flag.IntVar(&save, "save", 0, "whether to save the statistical info into 'statistic' table. 0 is disabled and 1 is enabled.")
张金富 已提交
985
	flag.StringVar(&saveTable, "savetb", DefaultStatisticTable, "the table to save 'statistic' info when save set 1.")
X
xieyinglin 已提交
986 987
	flag.IntVar(&thread, "thread", 10, "number of threads to import data.")
	flag.IntVar(&batch, "batch", 100, "rows of records in one import batch.")
张金富 已提交
988 989 990
	flag.IntVar(&auto, "auto", 0, "whether to use the startTime and interval specified by users when simulating the data. 0 is disabled and 1 is enabled.")
	flag.StringVar(&startTimeStr, "start", "", "the starting timestamp of simulated data, in the format of yyyy-MM-dd HH:mm:ss.SSS. If not specified, the earliest timestamp in the sample data will be set as the startTime.")
	flag.Int64Var(&interval, "interval", DefaultInterval, "time interval between two consecutive records, in the unit of millisecond. Only valid when auto is 1.")
X
xieyinglin 已提交
991 992 993 994
	flag.StringVar(&host, "host", "127.0.0.1", "tdengine server ip.")
	flag.IntVar(&port, "port", 6030, "tdengine server port.")
	flag.StringVar(&user, "user", "root", "user name to login into the database.")
	flag.StringVar(&password, "password", "taosdata", "the import tdengine user password")
张金富 已提交
995
	flag.IntVar(&dropdb, "dropdb", 0, "whether to drop the existing database. 1 is yes and 0 otherwise.")
X
xieyinglin 已提交
996 997 998 999 1000 1001
	flag.StringVar(&db, "db", "", "name of the database to store data.")
	flag.StringVar(&dbparam, "dbparam", "", "database configurations when it is created.")

	flag.Parse()
}

dengyihao's avatar
TD-935  
dengyihao 已提交
1002
func printArg() {
X
xieyinglin 已提交
1003 1004 1005 1006 1007
	fmt.Println("used param: ")
	fmt.Println("-cfg: ", cfg)
	fmt.Println("-cases:", cases)
	fmt.Println("-hnum:", hnum)
	fmt.Println("-vnum:", vnum)
X
xieyinglin 已提交
1008 1009 1010
	fmt.Println("-delay:", delay)
	fmt.Println("-tick:", tick)
	fmt.Println("-save:", save)
X
xieyinglin 已提交
1011
	fmt.Println("-savetb:", saveTable)
X
xieyinglin 已提交
1012 1013 1014
	fmt.Println("-thread:", thread)
	fmt.Println("-batch:", batch)
	fmt.Println("-auto:", auto)
张金富 已提交
1015
	fmt.Println("-start:", startTimeStr)
X
xieyinglin 已提交
1016 1017 1018 1019 1020 1021 1022 1023 1024
	fmt.Println("-interval:", interval)
	fmt.Println("-host:", host)
	fmt.Println("-port", port)
	fmt.Println("-user", user)
	fmt.Println("-password", password)
	fmt.Println("-dropdb", dropdb)
	fmt.Println("-db", db)
	fmt.Println("-dbparam", dbparam)
}