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

S
slguan 已提交
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
package main

import (
    "bufio"
    "flag"
    "fmt"
    "log"
    "os"
    "strconv"
    "strings"
    "sync"
    "sync/atomic"
    "time"

    "github.com/influxdata/influxdb1-client/v2"
)

type ProArgs struct {
    host           string
    username       string
    password       string
    db             string
    sql            string
    dataDir        string
    filesNum       int
    writeClients   int
    rowsPerRequest int
}

type WriteInfo struct {
    threadId int
    sID      int
    eID      int
}

type StatisInfo struct {
    totalRows int64
}

var statis StatisInfo

func main() {
    // Configuration
    var arguments ProArgs

    // Parse options
    flag.StringVar(&(arguments.host), "host", "http://localhost:8086", "Server host to connect")
    flag.StringVar(&(arguments.db), "db", "db", "DB to insert data")
    flag.StringVar(&(arguments.username), "user", "", "Username used to connect to server")
    flag.StringVar(&(arguments.password), "pass", "", "Password used to connect to server")
    flag.StringVar(&(arguments.sql), "sql", "./sqlCmd.txt", "File name of SQL commands")
    flag.StringVar(&(arguments.dataDir), "dataDir", "./testdata", "Raw csv data")
    flag.IntVar(&(arguments.filesNum), "numOfFiles", 10, "Number of files int dataDir ")
    flag.IntVar(&(arguments.writeClients), "writeClients", 0, "Number of write clients")
    flag.IntVar(&(arguments.rowsPerRequest), "rowsPerRequest", 100, "Number of rows per request")

    flag.Parse()
    statis.totalRows = 0

    if arguments.writeClients > 0 {
        writeData(&arguments)
    } else {
        readData(&arguments)
    }
}

func writeData(arguments *ProArgs) {
    log.Println("write data")
    log.Println("---- writeClients:", arguments.writeClients)
    log.Println("---- dataDir:", arguments.dataDir)
    log.Println("---- numOfFiles:", arguments.filesNum)
    log.Println("---- rowsPerRequest:", arguments.rowsPerRequest)

    var wg sync.WaitGroup
    wg.Add(arguments.writeClients)

    st := time.Now()

    a := arguments.filesNum / arguments.writeClients
    b := arguments.filesNum % arguments.writeClients
    last := 0
    for i := 0; i < arguments.writeClients; i++ {
        var wInfo WriteInfo
        wInfo.threadId = i + 1
        wInfo.sID = last
        if i < b {
            wInfo.eID = last + a
        } else {
            wInfo.eID = last + a - 1
        }
        last = wInfo.eID + 1
        go writeDataImp(&wInfo, &wg, arguments)
    }

    wg.Wait()

    elapsed := time.Since(st)
    seconds := float64(elapsed) / float64(time.Second)

    log.Println("---- Spent", seconds, "seconds to insert", statis.totalRows, "records, speed:", float64(statis.totalRows)/seconds, "Rows/Second")
}

func writeDataImp(wInfo *WriteInfo, wg *sync.WaitGroup, arguments *ProArgs) {
    defer wg.Done()

    log.Println("Thread", wInfo.threadId, "writing sID", wInfo.sID, "eID", wInfo.eID)

    // Connect to the server
    conn, err := client.NewHTTPClient(client.HTTPConfig{
        Addr:     arguments.host,
        Username: arguments.username,
        Password: arguments.password,
S
Shuduo Sang 已提交
128
	Timeout: 300 * time.Second,
S
slguan 已提交
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 233 234 235 236 237 238
    })

    if err != nil {
        log.Fatal(err)
    }

    defer conn.Close()

    // Create database
    _, err = queryDB(conn, fmt.Sprintf("create database %s", arguments.db), arguments.db)
    if err != nil {
        log.Fatal(err)
    }

    // Write data
    counter := 0
    totalRecords := 0

    bp, err := client.NewBatchPoints(client.BatchPointsConfig{
        Database:  arguments.db,
        Precision: "ms",
    })
    if err != nil {
        log.Fatal(err)
    }

    for j := wInfo.sID; j <= wInfo.eID; j++ {
        fileName := fmt.Sprintf("%s/testdata%d.csv", arguments.dataDir, j)
        fs, err := os.Open(fileName)
        if err != nil {
            log.Printf("failed to open file %s", fileName)
            log.Fatal(err)
        }
        log.Printf("open file %s success", fileName)

        bfRd := bufio.NewReader(fs)
        for {
            sline, err := bfRd.ReadString('\n')
            if err != nil {
                break
            }

            sline = strings.TrimSuffix(sline, "\n")
            s := strings.Split(sline, " ")
            if len(s) != 6 {
                continue
            }

            // Create a point and add to batch
            tags := map[string]string{
                "devid":    s[0],
                "devname":  s[1],
                "devgroup": s[2],
            }

            timestamp, _ := strconv.ParseInt(s[3], 10, 64)
            temperature, _ := strconv.ParseInt(s[4], 10, 32)
            humidity, _ := strconv.ParseFloat(s[5], 64)

            fields := map[string]interface{}{
                "temperature": temperature,
                "humidity":    humidity,
            }

            pt, err := client.NewPoint("devices", tags, fields, time.Unix(0, timestamp * int64(time.Millisecond)))
            if err != nil {
                log.Fatalln("Error: ", err)
            }

            bp.AddPoint(pt)
            counter++

            if counter >= arguments.rowsPerRequest {
                if err := conn.Write(bp); err != nil {
                    log.Fatal(err)
                }

                totalRecords += counter
                counter = 0
                bp, err = client.NewBatchPoints(client.BatchPointsConfig{
                    Database:  arguments.db,
                    Precision: "ms",
                })
                if err != nil {
                    log.Fatal(err)
                }
            }
        }

        fs.Close()
    }

    totalRecords += counter
    if counter > 0 {
        if err := conn.Write(bp); err != nil {
            log.Fatal(err)
        }
    }

    atomic.AddInt64(&statis.totalRows, int64(totalRecords))
}

func readData(arguments *ProArgs) {
    log.Println("read data")
    log.Println("---- sql:", arguments.sql)

    conn, err := client.NewHTTPClient(client.HTTPConfig{
        Addr:     arguments.host,
        Username: arguments.username,
        Password: arguments.password,
S
Shuduo Sang 已提交
239
	Timeout: 300 * time.Second,
S
slguan 已提交
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
    })

    if err != nil {
        log.Fatal(err)
    }

    defer conn.Close()

    fs, err := os.Open(arguments.sql)
    if err != nil {
        log.Printf("failed to open file %s", arguments.sql)
        log.Fatal(err)
    }
    log.Printf("open file %s success", arguments.sql)

    bfRd := bufio.NewReader(fs)

    for {
        sline, err := bfRd.ReadString('\n')
        if err != nil {
            break
        }

        sline = strings.TrimSuffix(sline, "\n")

        st := time.Now()

        _, err = queryDB(conn, sline, arguments.db)
        if err != nil {
            log.Fatal(err)
        }

        elapsed := time.Since(st)
        seconds := float64(elapsed) / float64(time.Second)

        log.Println("---- Spent", seconds, "seconds to query ", sline)
    }
}

func queryDB(conn client.Client, cmd string, db string) (res []client.Result, err error) {
    query := client.Query{
        Command:  cmd,
        Database: db,
    }

    response, err := conn.Query(query)
    if err == nil {
        if response.Error() != nil {
            return res, response.Error()
        }
        res = response.Results
    } else {
        return res, err
    }

    return res, nil
}