httpTestNew.go 5.0 KB
Newer Older
S
slguan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 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 42 43 44 45 46 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 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
package main

import (
	"bytes"
	"encoding/json"
	"flag"
	"fmt"
	"io/ioutil"
	"math/rand"
	"net/http"
	"os"
	"sync"
	"sync/atomic"
	"time"
)

var (
	token    string
	url      string
	config   Config
	request  int64
	begin    time.Time
	errorNum int64
)

type Config struct {
	HostIp      string `json:"hostIp"`
	TableNum    int    `json:"tableNum"`
	DbName      string `json:"dbName"`
	MetricsName string `json:"metricsName"`
	DataNum     int    `json:"dataNum"`
	BatchNum    int    `json:"batchNum"`
}

type TokenResult struct {
	Status string `json:"status"`
	Code   int    `json:"code"`
	Desc   string `json:"desc"`
}

type JsonResult struct {
	Status string `json:"status"`
	Code   int    `json:"code"`
}

func readFile(filename string) {
	file, err := os.Open(filename)
	if err != nil {
		println("taos.json not found")
		panic(err)
	}
	defer file.Close()

	dec := json.NewDecoder(file)
	err = dec.Decode(&config)
	if err != nil {
		println("taos.json parse error")
		panic(err)
	}

	request = 0
	errorNum = 0

	fmt.Println("================config parameters======================")
	fmt.Println("HostIp:", config.HostIp)
	fmt.Println("TableNum:", config.TableNum)
	fmt.Println("dbName:", config.DbName)
	fmt.Println("metricsName:", config.MetricsName)
	fmt.Println("dataNum:", config.DataNum)
	fmt.Println("batchNum:", config.BatchNum)

	fmt.Println("================http token=============================")
	token, err = getToken()
	url = fmt.Sprintf("http://%s:%d/rest/sql", config.HostIp, 6020)

	fmt.Println("httpToken:", token)
	fmt.Println("httpUrl:", url)

	if err != nil {
		panic(err)
	}
}

func getToken() (string, error) {
	resp, err := http.Get(fmt.Sprintf("http://%s:%d/rest/login/%s/%s", config.HostIp, 6020, "root", "taosdata"))
	if err != nil {
		return "", err
	}

	defer resp.Body.Close()

	var tokenResult TokenResult

	data, err := ioutil.ReadAll(resp.Body)

	if err != nil {
		return "", err
	}

	err = json.Unmarshal(data, &tokenResult)
	if err != nil {
		return "", err
	}

	if tokenResult.Status != "succ" {
		fmt.Println("get http token failed")
		fmt.Println(tokenResult)
		return "", err
	}

	return tokenResult.Desc, nil
}

func exec(client *http.Client, sql string) {
	for reTryTimes := 0; reTryTimes < 10; reTryTimes++ {

		req, err1 := http.NewRequest("POST", url, bytes.NewReader([]byte(sql)))
		if err1 != nil {
			continue
		}
		req.Header.Add("Authorization", "Taosd "+token)

		resp, err := client.Do(req)

		if err != nil {
			continue
		}

		data, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			resp.Body.Close()
			continue
		}

		var jsonResult JsonResult
		err = json.Unmarshal(data, &jsonResult)
		if err != nil {
			resp.Body.Close()
			continue
		}

		if jsonResult.Status != "succ" {
			resp.Body.Close()
			continue
		}

		atomic.AddInt64(&request, 1)

		if (request*int64(config.BatchNum))%100000 == 0 && request != 0 {
			spend := time.Since(begin).Seconds()
			if spend >= 1 && spend < 10000000 {
				total := (request - errorNum - 2 - int64(config.TableNum)) * int64(config.BatchNum)
				fmt.Printf("request:%d, error:%d, insert:%d, spend:%.2f seconds, dps:%.1f \n", request, errorNum, total, spend, float64(total)/float64(spend))
			}
		}

		return
	}

	//fmt.Println("exec failed, sql:", sql)
	errorNum++
}

func createDb() {
	fmt.Println("================create database =====================")

	client := &http.Client{}
	sql := fmt.Sprintf("create database %s", config.DbName)
	exec(client, sql)
}

func createTb() {
	fmt.Println("================create table ========================")

	client := &http.Client{}
	sql := fmt.Sprintf("create table %s.%s(ts timestamp, f1 int, f2 int) tags (tb int)", config.DbName, config.MetricsName)
	exec(client, sql)

	for i := 0; i < config.TableNum; i++ {
		sql := fmt.Sprintf("create table %s.t%d using %s.%s tags(%d)", config.DbName, i, config.DbName, config.MetricsName, i)
		exec(client, sql)
	}
}

func insertData(wg *sync.WaitGroup, tableIndex int) {
	defer wg.Done()

	client := &http.Client{}
	beginTime := int64(1519833600000)

	for i := 0; i < config.DataNum; i += config.BatchNum {
		var sql bytes.Buffer
		sql.WriteString(fmt.Sprintf("insert into %s.t%d values", config.DbName, tableIndex))

		for j := 0; j < config.BatchNum; j++ {
			sql.WriteString(fmt.Sprintf("(%d,%d,%d)", beginTime+int64(i)+int64(j), rand.Intn(1000), rand.Intn(1000)))
		}
		exec(client, sql.String())
	}
}

func main() {
	filename := flag.String("config", "http.json", "config file name")

	flag.Parse()

	readFile(*filename)

	fmt.Println("\n================http test start======================")

	createDb()
	createTb()

	begin = time.Now()

	var wg sync.WaitGroup

	fmt.Println("================insert data  ========================")
	for i := 0; i < config.TableNum; i++ {
		wg.Add(1)
		go insertData(&wg, i)
	}

	wg.Wait()

	fmt.Println("\n================http test stop ======================")

	spend := time.Since(begin).Seconds()

	total := (request - errorNum - 2 - int64(config.TableNum)) * int64(config.BatchNum)
	fmt.Printf("request:%d, error:%d, insert:%d, spend:%.2f seconds, dps:%.1f \n", request, errorNum, total, spend, float64(total)/float64(spend))
}